2、在树莓派终端输入 ls /dev/tty*查看两者连接端口的名字。查看有没有ttyACM0 这个文件(注只有在两个硬件USB互连的情况下才会有这个。如果两者没有连接是不会有的) 最新的系统一般都会自动生成。看到ttyACM0就说明二者可以通讯了。
3、编写树莓派与arduino通信代码。
arduino代码:
void setup()
Serial.begin(9600); // 9600 bps
void loop()
if ( Serial.available())
if('s' == Serial.read())
Serial.println("Hello Raspberry,I am Arduino.");
}
把上面代码通过python IDE下载到arduino中,然后再再与树莓派usb链接。
树莓派代码:
import serial #import serial module
ser = serial.Serial('/dev/ttyACM1', 9600,timeout=1); #open named port at 9600,1s timeot
#try and exceptstructure are exception handler
while 1:
ser.write('s');#writ a string to port
response = ser.readall();#read a string from port
print response;
except:
ser.close();
我这里把上面代码在树莓派中保存为communication.py文件。
2、在树莓派终端输入sudo python communication.py运行程序。
显示结果:
此图是两者之间的通信结果:树莓派向arduino发送一个字符‘s’,arduino向树莓派回复字符串“hello raspberry,i am arduino”。