Raspberry Pi& Arduino读取串行传感器数据

时间:2016-06-28 19:35:05

标签: python python-2.7 arduino raspberry-pi raspberry-pi3

我有一个电压传感器连接到我的Arduino uno,后者又连接到我的Raspberry Pi 3.我想从Arduino到Raspberry Pi以乒乓式方式获取传感器信息。我将通过cronjob上的Python脚本发送的字符唤醒它,并将传感器值抓取并放入mysql数据库。

将来我想为Arduino添加更多传感器

当我运行python代码时,我遇到的问题是Python端我得到一个空白的黑线。

Raspberry Pi 3 Python代码:

#!/usr/bin/python

import serial 
import MySQLdb
import time

db = MySQLdb.connect(host="localhost",    
                 user="user",        
                 passwd="password", 
                 db="database")        

cur = db.cursor()

port = serial.Serial("/dev/ttyACM0", baudrate = 9600, timeout=None)
port.flushInput()      

sensor1 = 0;
sensor2 = 0;
sensor3 = 0;

vals = []

while (port.inWaiting()==0):
port.write("*")
time.sleep(1)

vals = (port.readline()).split(',')
print vals
sensor1 = int(vals[0])
sensor2 = int(vals[1])
sensor3 = int(vals[2])
cur.execute("insert into voltage(volts) values(" + str(Battout) + ")" ) 

cur.execute("SELECT * from voltage")

db.close()

Arduino代码:

const int BattVolt = A0;

int BattVal = 0;
float Battout;          

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


void loop() {

Serial.flush();
while(!Serial.available());  //wait for character from raspi
delay(1000);

float Voltage;
BattVal = analogRead(BattVolt);  //read analog pins
Voltage=BattVal/4.09;
Battout=(Voltage/10);

Serial.print(Battout);
Serial.print(",");

}

2 个答案:

答案 0 :(得分:2)

对您的实施的一些观察。

  1. 为什么在python脚本中使用Battout

  2. 在python脚本中,您需要一行(这意味着字符串以'\ n'结尾),但在Arduino C ++代码中,您使用print代替println或添加换行。

  3. 显然你希望在python脚本中收到类似“12,32,15”的东西,但是如果你只向Arduino发送一个字符,那么它只会进行主循环的1次迭代。

答案 1 :(得分:0)

Raspberry Pi 3和uart0(蓝牙)uart1(串行)存在问题。
对于Pi 3 uart1通常可在/dev/ttyS0上找到{1}}和TX-GPIO 14,RX-GPIO 15.
uart1的波特率取决于核心时钟。因此,如果核心时钟发生变化,波特率将会发生变化!
解决方法1:/boot/config.txt中,添加第core_freq=250行。保存并重启!现在你的Pi有一个恒定的核心频率。 Raspberry Pi 3 UART baud rate workaround
解决方法2 :更改设备树,使用uart0进行串行通信,使用uart1进行蓝牙处理(蓝牙现在也一样)。Raspberry Pi 3 compatibility (BT disable & serial port remap fix)

相关问题