简单介绍一下:arduino和树莓派通信,Python3 和Python2的版本对于编码有不同的方法,不注意的话会使通信来说就形成错误,或者运行出错,发现3 的版本代码,python2也能实现,反过来就不行。
问题解决:
代码简介
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
....
总结
这其实就是很简单的编码问题,
Python 2 将字符串处理为 bytes 类型。
Python 3 将字符串处理为 unicode 类型。