arduino与树莓派通信的版本编码问题 - 夜owl - 博客园
:arduino与树莓派通信,Python3 和Python2的版本有不同的编码方法。如果你不注意它,它会导致通信错误或操作错误。 的版本代码,python也可以实现,反之亦然。
代码简介
arduino代码
volatile float dist; float checkdistance_4_7() { digitalWrite(4, LOW); delayMicroseconds(2); digitalWrite(4, HIGH); delayMicroseconds(10); digitalWrite(4, LOW); float distance = pulseIn(7, HIGH) / 58.00; delay(10); return distance; } void setup(){ Serial.begin(9600); dist = 0; pinMode(4, OUTPUT); pinMode(7, INPUT); } void loop(){ dist = checkdistance_4_7(); //Serial.println(String(dist) String("cm")); if ( Serial.available()) { if('s' == Serial.read()) Serial.println(dist); } }
Python2正常运行代码
# -*- coding:UTF-8 -*- import serial #import serial module ser = serial.Serial('/dev/ttyACM0', 9600,timeout=1); #open named port at 9600,1s timeot #try and exceptstructure are exception handler try: while 1: ser.write('s');#writ a string to port response = ser.readall();#read a string from port print response; except: ser.close();
7.28 10.28 ...
Python3的运行代码
# -*- coding:UTF-8 -*- import serial #import serial module ser = serial.Serial('/dev/ttyACM0', 9600,timeout=1); #open named port at 9600,1s timeot #try and exceptstructure are exception handler try: while 1: ser.write('s'.encode('utf-8'));#writ a string to port response = ser.readall()#read a string from port print(response) except: ser.close(); print(111)
输出
b'7.28\r\n' b'10.28\r\n' ...
对比可以知道函数语法不同:
ser.write('R'.encode()); print (response);
Python3.转换编码代码
# -*- coding:UTF-8 -*- import serial #import serial module ser = serial.Serial('/dev/ttyACM0', 9600,timeout=1); #open named port at 9600,1s timeot #try and exceptstructure are exception handler try: while 1: ser.write('s'.encode('utf-8'));#writ a string to port response = ser.readall().decode()#read a string from port print(response) except: ser.close(); print(111)
不同点
response = ser.readall().decode()#read a string from port
最终实现效果跟2 一样。还有。还有python2也能运行
7.28 10.28 ...
这实际上是一个非常简单的编码问题,