0x01.About
之前写过一篇关于Arduino通过串口与Raspberry通信的文章,http://homeway.me/2015/04/08/raspberry-connect-to-arduion-by-serial/,后来找到解决办法,通过主动唤醒被动。让一方主动发起通信,类似心跳包,另一方只保持等待读取一行,这样就不会导致双方同时存在一个计时器,定时发送数据。
0x02.Coding
这里蓝牙串口默认波特率9600,所以先要修改树莓派串口波特率:http://blog.miguelgrinberg.com/post/a-cheap-bluetooth-serial-port-for-your-raspberry-pi
首先做配对,关于蓝牙与蓝牙之间配对指令集,需要查阅说明书。
先是Arduino一方代码:
char line[512] = ""; // 传入的串行数据
int ret = 0;
void setup() {
Serial.begin(9600);
Serial.println("");
}
void loop() {
//纯口可用时操作
if (Serial.available() > 0) {
// 读取传入的数据: 读到\n为止,或者最多512个字符
ret = Serial.readBytesUntil('\n', line, 512);
Serial.println("Arduino Receive => " + line);
}
delay(300);
}
然后是关于树莓派代码:
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import time,sys
import serial
port = "/dev/ttyACM0"
class Communicate:
def __init__(self, device):
self.device = device
self.Seral = serial.Serial(device)
def send(self, msg):
self.Seral.write(msg)
print("Raspberry Send => " + time.strftime("%Y-%m-%d %X\t") + msg)
def readLine(self):
line = self.Seral.readline()
#print("Raspberry Receive => " + time.strftime("%Y-%m-%d %X\t") + line.strip())
return line
def main(self):
line = self.readLine()
while(line):
try:
line = self.readLine()
except EOFError:
print("No data")
if __name__ == '__main__':
try:
conn = Communicate(sys.argv[1] if len(sys.argv) > 1 else port)
conn.main()
except KeyboardInterrupt:
print("ERROR")
exit()
串口地址默认/dev/ttyACM0
,可以移植到电脑上,相应地修改串口地址就好了。
Python处理串口部分主要就是->接收->反馈。
本文出自 夏日小草,转载请注明出处: http://homeway.me/2015/06/13/raspberry-connect-to-arduion-by-bluetooth/
by 小草
2015-06-13 22:46:20