본문 바로가기
파이썬

파이썬 바이너리파일 쓰기 -#9

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

이제 문자, 문자열, 숫자를 썩어서 아두이노에서 전송해 보자.

 

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


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

//    Serial.println(sizeof(int));   
//    Serial.println(sizeof(float));     
//    Serial.println(sizeof(double));   
}

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

    return ;
}

 

 

#숫자 데이터를 읽고 쓰기 
import struct
import serial, time 

#원도우용으로 시리얼 포트를 연다.
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, age, height, weight) = struct.unpack('=20shff', data)
                    print('data:  {0}, {1}, {2:d}, {3:.2f}, {4:.3f}'.format(cc, ss, age, height, weight))

            time.sleep(1) 
except (KeyboardInterrupt, SystemExit):
    print("Exit...")
 
finally:
    ser.close()
print("Good by!")

 

댓글