C:小尾巴

我正尝试在Raspberry Pi(使用C编程)和Arduino(使用Arduino IDE)之间发送和接收数据。

根据我在互联网上可以find的,它指向我,都是在小端格式。

我使用串行通信(RS232)与teuniz.net/RS-232上的“Linux和Windows的RS-232”库在它们之间发送整数

据我所知,如果两者都是小端格式的话,我不需要在这些位上进行任何移位。 不过,在我的下面的代码中,我需要移动由Arduino读入的位。 我不知道为什么我需要执行位移当两者都是小端(为了获得正确的数据)。 无需再费周折….

C代码:

unsigned char buf[4]; int g = 100; memcpy(buf, (char*)&g, sizeof(int)); // port 24 for ttyACM0 if(RS232_SendBuf(24, buf, sizeof(int)) == -1) { // error processing here } 

Arduino代码:

 long a[4]; long value = 0; void loop(){ if(Serial.available()>=4){ for(int i = 0; i < 4 ; i++){ a[i] = Serial.read(); } // Over here i need to shift the LSB of the byte received to the MSB of the long var until the MSB of byte becomes LSB of long var // i do not have the code which is faulty right now as its already past midnight and my group mates are already asleep so I will post again in the morning value += a[0]; value += a[1] << 8; value += a[2] << 16; value += a[3] << 24; Serial.println(value); // now it prints out 100 correctly value = 0; } } 

将不胜感激所有帮助! 对不起还有C和endian的新手!

更新:我想我知道为什么以上发生! 请在下面评论让我知道,如果我的假设是对的/错的!

我正在发送170的int值170.hex是0x000000aahex。 当我memcpy(这是小endian进来),它被存储为一个00 00 00(LSB到MSB)。 所以当我在arduino中得到这个值的时候,我肯定会需要做一个整数从MSB读到LSB的转换(因为在arduino中没有内存复制/读取,所以我不在乎任何endian问题)。

但是,由于Arduino处理速度慢(它有很多其他的东西来计算!!),我可以让我的C代码,使:

 int g = 170; unsigned char buf[4]; // below line not needed anymore?? //memcpy(buf, (char*)&g, sizeof(long)); if(RS232_SendBuf(24, (char *)&g, sizeof(int)) == -1) { ... } 

想听更多,所以我可以学习更多! 当我问这个问题的时候,看起来我的基础知识是错误的!

你的代码对我来说看起来很好(我还没有运行它)。

  • 假设你有整数0xaabbccdd
  • 在Pi上,“buf”将包含ddccbbaa 。 他们会按照这个顺序发送。
  • 在arduino上, a也包含ddccbbaa
  • 然后创建value (dd << 0) + (cc << 8) + (bb << 16) + (aa << 24) ,给出0xaabbccdd

你正在解析一个32位的小端值,而不是一个大的端值。 第一个字节以最低有效位结束; 最后一个字节以最高有效字节结束。

如果您正在转换包含大端值的缓冲区,则代码如下所示:

 uint8_t a[4]; int value = 0; for ( int i = 0; i < 4; ++i ) { value << 8 * i; // shift everything over one byte value += a[ i ]; // add the next byte to the LSByte } 

你看到了不同?