【问题标题】:Error in sending entire variable from raspberrypi (python) to arduino将整个变量从 raspberrypi (python) 发送到 arduino 时出错
【发布时间】:2019-08-31 16:51:16
【问题描述】:

我想通过串行通信将存储在变量“int3”中的数字“500”从 python 传输到 arduino。 arduino 使用 Serial.read() 读取数据,但只打印“5”。 提前致谢。 我有 int3、字节 2 和字节 3 要从 python 发送,但希望 arduino 打印 int3 的值。

import serial
import time
ser=serial.Serial('/dev/ttyACM0',9600)
int3 = 500
int3 = b'%d' %int3
while (1):

    ser.write(int3)
    ser.write(b'2')
    ser.write(b'3')
#print type(ser.write)
    time.sleep(1)
    print(int3)
String r;

void setup(){
  Serial.begin(9600);
//  while(!Serial)
//  {
//    ;
//  }
}
void loop(){
  if(Serial.available() > 0){  
    r =(Serial.read() - 0);  //conveting the value of chars to integer
Serial.print(r[0]);


delay(100);
//while(Serial.available () !=0) r=Serial.read();
}



}

【问题讨论】:

  • 因为Serial.read 只返回第一个传入字节。 delay 阻止应用程序,因此其他两个字节被丢弃。
  • 我应该删除延迟吗?
  • 如果我想要所有三个字节有什么解决方案?
  • 为什么不以二进制(和固定长度)形式发送int 而不是转换两次?
  • 创建一个循环,检查一个字节是否可用,当可用时将字节添加到缓冲区,当缓冲区满时离开循环,接收到停止或其他一些条件。

标签: arduino pyserial serial-communication


【解决方案1】:

将 if 替换为 while 循环:

String fromRaspberry;
void loop(){
  char c;
  while (Serial.available() > 0) {  
    c = Serial.read(); //read char
    fromRaspberry += c; //add the read char to string
  }
  int x = fromRaspberry.toInt(); //convert string to int
  Serial.println(x);
  // clear the string for new input:
  fromRaspberry = "";
}

【讨论】:

  • 谢谢。这是工作。但是,如果我尝试发送三个变量,例如 int1= 100、int2=250、int3=350。当我使用时,你的建议。我得到了所有变量的值,但现在,我只想打印 int1(即 100)的值。如果我尝试,Serial.println(r[0],),arduino 串行监视器会根据需要打印“1”而不是“100”。
  • 在每个从树莓派发送的 int 之后添加一个分隔符,例如换行符,并检查该字符。当你收到一个新行时,你就知道你收到了一个完整的 int。查看此示例以了解如何查找换行符:arduino.cc/en/Tutorial.StringToIntExample
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-20
  • 1970-01-01
  • 2020-08-09
  • 2019-05-26
相关资源
最近更新 更多