본문 바로가기
아두이노/유선통신

아두이노 2대를 이용한 정수와 실수 전송-#7(최종)

by 오징어땅콩2 2020. 8. 7.
반응형

사실 지금까지 할 것은 다 했다.

오늘 소스코드는 생각보다 아주 간단하게 변경되었다.

지금까지 교육을 목적으로 길게 표현했지만,

결국 한 문장으로 압축된다.

보내는 것도 한문자 받는 것도 한 문장이다.

 

결국 데이터를 주고받고는 한문 장로 끝나는 것이다.

이것이 시리얼통신이던 블루투스이던 와이파이던 다른 무선 통인이던 모두 동일하다.

결국 한 문장으로 데이터를 주고받는다.

사실 소프트웨어 하는 사람은 주고받고는 관심 없다. 

단지 주기만 주면 되고 받기만 받으면 된다.

실제 주고받는 것은 하드웨어 블루투스, 와이파이, 로라 등등 다른 하드웨어가 하는 일이지,

코딩 소프트웨어가 하는 일은 아니다.

 

단지 주의할 것은 정수가 아두이노에서는 2바이트인데, 윈도에서는 4바이트다. 

사실 본인은 귀찮아서 정수도 실수에 실어 보낸다. 

또 주의할 것은 CPU에 따라서 바이트가 뒤집어 전송되기도 한다. 

리털 인디언이니 빅 인디 안이니 하는 용어도 나온다. 

물론 지금 다 알 필요는 없다. 그때 가서 공부하면 된다.

 

항상 본인이 강조하는 것은 문법 하나하나를 알라고 하지 말라는 것이다.

단지 개념을 먼저 이해하기 바란다는 것이다.

 

        sSerial.write((char*)&a, sizeof(Info));
 
        sSerial.readBytes((char*)&a, sizeof(Info));

 

#include <SoftwareSerial.h>
 
typedef struct _Info
  int heartrate;
  int servo_degree;
  double temp1;
  double temp2;
  char str[25];
  _Info()
  {
    
  }
}Info;
 
 
SoftwareSerial sSerial= SoftwareSerial(23);
//HardwareSerial&  sSerial = Serial2;
 
Info a;
volatile unsigned long previousMillis;
void setup() 
{
    Serial.begin(9600);
    sSerial.begin(9600);  
    previousMillis = millis();  
 
    Serial.println(sizeof(int));   
    Serial.println(sizeof(float));     
    Serial.println(sizeof(double));   
 
    a.heartrate =200;
    a.servo_degree = 80;
    a.temp1 = 25;
    a.temp2 = 30;
    strcpy(a.str, "hi hi");
}
 
void loop() 
{
    unsigned long currentMillis = millis();
    if ((currentMillis-previousMillis)> 1000*1)
    {
        sSerial.write((char*)&a, sizeof(Info));
        previousMillis = currentMillis;
    }
 
    return ;
}

 

받는쪽

#include <SoftwareSerial.h>
 
typedef struct _Info
  int heartrate;
  int servo_degree;
  double temp1;
  double temp2;
  char str[25];
  _Info()
  {
    
  }
}Info;
 
SoftwareSerial sSerial= SoftwareSerial(23);
//HardwareSerial&  sSerial = Serial2;
 
Info a;
void setup() 
{
    Serial.begin(9600);
    sSerial.begin(9600);     
}
 
void loop() 
{
    if (sSerial.available())
    { 
         sSerial.readBytes((char*)&a, sizeof(Info));
         
          Serial.print(a.heartrate);  Serial.print(" ");  
          Serial.print(a.servo_degree); Serial.print(" ");  
          Serial.print(a.temp1);  Serial.print(" ");  
          Serial.print(a.temp2);  Serial.print(" ");  
          Serial.print(a.str);    Serial.print(" ");                                 
          Serial.println();                       
    }
    
    return ;
}