标签:c-3 linux endianness arduino raspberry-pi
我正在尝试发送&在Raspberry Pi(使用C编程)和& ;;之间接收数据. Arduino(使用Arduino IDE).
基于我在互联网上可以找到的东西,它指向我两者都是小端格式.
我在teuniz.net/RS-232上使用串行通信(RS232)与“RS-232 for Linux and Windows”库发送整数
根据我的知识,如果两者都是小端格式,我不需要对位进行任何移位.但是,在我的情况下使用下面的代码,我需要移位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的新手!
更新:我想我知道为什么会发生这种情况!如果我的假设是对错的,请在下面评论以告诉我!
我在C中发送一个170的int值.在十六进制中,170是0x000000aa.当我记忆(这是小端进来的地方)时,它被存储为a 00 00 00(LSB到MSB).所以当我得到arduino中的值时,我肯定需要进行移位,因为从MSB到LSB读取整数(因为在arduino中没有内存复制/读取,我不关心这里的任何字节序问题).
但是,由于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”将包含dd,cc,bb,aa.他们将按顺序发送到网上.
>在arduino上,a还包含dd,cc,bb,aa.
>然后创建值为(dd<< 0)(cc << 8)(bb<< 16)(aa<<<<<<<<<<<<<#24),给出0xaabbccdd.
标签:c-3,linux,endianness,arduino,raspberry-pi 来源: https://codeday.me/bug/20190702/1355391.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。