본문 바로가기
파이썬

파이썬, 데이터베이스 그리고 아두이노 통신 -#2

by 오징어땅콩2 2021. 10. 6.
반응형

아두이노쪽에서 31바이틀 보내오고 있지만, 데이터베이스에서는 더 많은 데이터를 저장하고 있다.

추가된 내용은 순번, 날짜시간이다. 

이것 또한 개인 취향이기는 한데, 순번과 날짜시간이 같이 저장된다면 나중에 데이터분석에 용의 할 것이다.

그렇다고 날짜, 시간을 아두이노에서 구할 필요는 없다. 

만약 구한다면 어리석은 일이다. 

한마디로 굳이라고 할 수있다.

 

import struct
import serial, time 
import sqlite3
import datetime

#먼저 메모리에만 저장(임시)
#con = sqlite3.connect(":memory:")
#데이터베이스 파일에 저장
con = sqlite3.connect("arduino.db")

#커서 객체를 생성
cur = con.cursor()
#테이블 구조를 만들기(테이블 스키마 생성)

cur.execute("SELECT count(name) FROM sqlite_master WHERE type='table' AND name='Experiment';");
if cur.fetchone()[0]==1:
    print('Table exists.')
else:
    cur.execute("create table Experiment (id integer primary key autoincrement,  date text, explanation text, ivalue integer, dvalue1 real, dvalue2 real);")

#원도우용으로 시리얼 포트를 연다.
ser = serial.Serial(port = "com3", baudrate=9600, timeout=2)

if (ser.isOpen() == False):
    ser.open()
#만약 ttyAMA0에 데이터가 남아있으면 비우고 새로 시작한다.
ser.flushInput()
ser.flushOutput()
try:
    while True:
        if ser.readable():
            cc = ser.read(1)
            #cc = struct.unpack('=c', data)
            if cc == b'1' :
                data = ser.read(30)
                if len(data)==30:
                    (ss, iv1, dv1, dv2) = struct.unpack('=20shff', data)
                    text1 = str(ss.decode('utf-8')).rstrip('\x00')
                    print('data:  {0}, {1}, {2:d}, {3:.2f}, {4:.3f}'.format(cc, text1,  iv1, dv1, dv2))
                    now = datetime.datetime.now() # 현재 시간 삽입
                    nowDatetime = now.strftime('%Y-%m-%d %H:%M:%S') # 사람이 보기 좋게 포맷함수로 바꿔준다.                    
                    cur.execute("insert into Experiment (date, explanation, ivalue, dvalue1, dvalue2) values (?, ?, ?, ?, ? );", (nowDatetime, text1,  iv1, dv1, dv2))
                    con.commit() 
            time.sleep(0.1) 
except (KeyboardInterrupt):
    print("Exit...")
 
finally:
    #연결을 끊고 나가기     
    ser.close()
    con.close()     
    print("Good by!")

 

typedef struct _Info
{ 
  char cc;
  char ss[20];
  int ivalue;
  double dvlaue1;
  double dvlaue2;
  _Info()
  {
    cc = '1';
    strcpy((char*)(ss), "arduino is best");
    ivalue =30;
    dvlaue1 = 1024.0;
    dvlaue2 = 768.1;    
  }
}Info;


Info a;
volatile unsigned long previousMillis;
void setup() 
{
    Serial.begin(9600);
    previousMillis = millis();  

}

void loop() 
{
    unsigned long currentMillis = millis();
    if ((currentMillis-previousMillis)> 1000*1)
    {
        //Serial.println(sizeof(Info));  
        Serial.write((char*)&a, sizeof(Info));
        previousMillis = currentMillis;
    }

    return ;
}

 

댓글