簡體   English   中英

PC和Arduino之間的串行通信

[英]Serial communication between PC and Arduino

我已經為Arnuino編寫了一個程序,該程序將一個聯合發送的結構發送到PC上的程序。 該結構必須為整數,但我沒有得到正確的輸出。 PC上的程序將boost庫用於串行連接。 並以64位版本(與vs2010)一起構建和編譯。

如果我在聯合體內具有單個整數變量,則該代碼有效。 但是,帶有工會的結構不起作用。 只有一個整數獲取數據,並且該數據是錯誤的。

我會造成64位(pc)和32位(Ardunio)問題嗎? 誰能幫我這個忙。 提前致謝。

PC代碼段(省略了串行設置):

union packed{
  struct test{
  unsigned int data;
  unsigned int data2;
} struc;

 unsigned char bytes[8];
}SerialPacked;

  SerialPacked.struc.data = 0;
  SerialPacked.struc.data2 = 0;

  cout << "Data before: " << SerialPacked.struc.data << endl;
  cout << "Data2 before: " << SerialPacked.struc.data2 << endl;

  read(port,buffer((unsigned char*)&SerialPacked.bytes[0], 1));
  read(port,buffer((unsigned char*)&SerialPacked.bytes[1], 1));
  read(port,buffer((unsigned char*)&SerialPacked.bytes[2], 1));
  read(port,buffer((unsigned char*)&SerialPacked.bytes[3], 1));
  read(port,buffer((unsigned char*)&SerialPacked.bytes[4], 1));
  read(port,buffer((unsigned char*)&SerialPacked.bytes[5], 1));
  read(port,buffer((unsigned char*)&SerialPacked.bytes[6], 1));
  read(port,buffer((unsigned char*)&SerialPacked.bytes[7], 1));

  cout << "Data after: " << SerialPacked.struc.data << endl;
  cout << "Data2 after: " << SerialPacked.struc.data2 << endl;

Arduino代碼:

int ledPin = 13;


union packed{
    struct test{
      unsigned int data;
      unsigned int data2;
}struc;
    unsigned char bytes[8];
} 
SerialPacked;

void setup() {  
    pinMode(ledPin, OUTPUT); 
    Serial.begin(9600); 

   SerialPacked.struc.data = 0;
   SerialPacked.struc.data2 = 0;
};




void loop() {

while(1){
  digitalWrite(ledPin,HIGH);
  SerialPacked.struc.data = SerialPacked.struc.data + 1;
  SerialPacked.struc.data2 = SerialPacked.struc.data2 + 1;;

  for(int i=0;i <8; i++){ 
    Serial.write(SerialPacked.bytes[i]);
  };

    digitalWrite(ledPin,LOW);
    delay(1000);
 };

}

問題是Arduino上的int 是兩個字節 ,但是PC上的int可能是四個字節。 根據您的編譯器,可能會有一個開關可用於設置int的大小,也可以只使用更明確的類型。 使用int的想法是,通過采用宿主平台的自然大小,可以使代碼輕松地從一個平台適應另一個平台。 但是,出於同樣的原因,這不是在平台之間傳輸數據的好選擇。

要確認這是問題,請嘗試讀取的字節出SerialPacked ,而不是訪問struc 我敢肯定,您會發現所有數據都在那里-這就是您嘗試讀取數據的方式。

我已經解決了,請整理一下...我將Arduino代碼的結構中的整數更改為longs。 數據正確無誤。

這是因為32位Ardunio上的long與64位vs2010代碼上的整數大小相同嗎? 還是我在這里想念什么? 感謝您的反饋!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM