Arduino的串口通信(serial) 延迟大、有乱码,一点小经验

最近在配arduino和pc的串口通信,遇到下面些问题

延迟大

我用了Serial.parseInt()读数据,奇怪的发现总是有一秒的延迟,更奇怪的是串口监视器好好地秒回。我一开始怀疑是python的读写切换出了问题,后来才发现是我传回去的字符串,最后一个数字后面没有加空格或者其他空白字符,而这个parseInt是一个阻塞式的函数,这样就玄学停顿若干时长了。

出现\xff、\x00这样的情况

出现乱码(arduino返回收到的字符,串口监视器来监视)

上面俩都是一个原因,没有考虑到串口的传送速度,这个是由比特率决定的,如果9600bps,那么0.8ms左右会收到一个字节(怪不得缓冲区这么小),那么至少delay(1),而且是理想状态下,没有考虑中间函数。也就是说你如果不用Serial.available,直接用serial.read,或者是连续两次用serial.read,很可能读到\xff、\x00,也就是串口监视器所出现的乱码。

总结

以上就是我遇到的坑,总之用read的时候你只能保证读到一个字符,需要搭配available和大循环使用,用parseInt的时候,你传下来的字符串得有空白符。
希望能帮到你!

另外

附上我检测的代码吧,分别用在python和arduino uno
ser.py

#coding=utf-8
import time
import serial 
import sys
port = '/dev/ttyUSB0' #linux
#port = 'com9'#windows
class Ser:
    def __init__(self, _port='/dev/ttyUSB0', _bitrate = 115200, _timeout = 0.1):
        self.port = _port
        self.bitrate = _bitrate
        self.timeout = _timeout
        self.connecting = False
        self.connect()

    def connect(self):
        while not self.connecting:
            try:
                time.sleep(1)
                print("try")
                self.com = serial.Serial(self.port, self.bitrate, timeout=self.timeout) 
                self.connecting = True
                print("ok")
                break
            except KeyboardInterrupt:
                print("KeyboardInterrupt")
                sys.exit(0)
            except:
                print("fail")

    def info(self):
        print(self.com)
    
    def setPort(self, _port):
        self.port = _port
        self.connect()

    def setBitrate(self, _bitrate):
        self.bitrate = _bitrate
        self.connect()

    def setTimeout(self, _timeout):
        self.timeout = _timeout
        self.connect()
    
    def available(self):
        return self.connecting
        
    def get(self):
        ch = ' '
        if self.com.inWaiting():
            ch = self.com.read()
            print(ch)
        return ch
    
    def put(self, str):
        print("writing:"+str)
        self.com.write(str.encode("utf-8"))
        print("done")
    
def detect():
    time.sleep(0.05)
    
if __name__ =='__main__':
    com = Ser(port)
    while True:
        if com.get()==b'@':
            detect()
            com.put("# 10 2 3 5 7 31 25 68 24 2 3 5 7 31 25 68 24 31 25 68 24 2 3 5 7 31 25 68 24 2 3 5 7 31 25 68 24 31 25 68 9 ")
        #break
        
    

test_serial.ino

int num = 0; 
bool not_waiting = 1; //判断和上位机通讯是不是可用
int get_data[100] = {0};
int cnt__ =  0;
int t1 = 2;
int t2 = 0;
int check = 0;

int get_positions(int &n,int a[])
{
  char head;
  int i,j;
  if (not_waiting)
  {
    Serial.print('@');
    not_waiting = 0;
    cnt__++;
  }
  else if (Serial.available())
  {
    head = Serial.read();
    if (head=='#')
    {     
      
      n = Serial.parseInt(); 
      for (i = 1;i<=4*n;i++)
      {
        a[i] = Serial.parseInt();  
      }
      not_waiting = 1;//不知道这样会不会出问题
      check = a[4*n];
      return 1;
    }
  }
  return 0;
}

void setup() 
{
	Serial.begin(115200);
}

void loop() 
{
	if(get_positions(num,get_data))
	{
	  Serial.print(check);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

萧易风船长

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值