我有一个连接到运行 Arch 的 Raspberry Pi 的 Arduino。
arduino 没有什么可做的,只是不断地打印一些传感器数据:
#include<Arduino.h>
void setup() {
Serial.begin(9600);
}
float temp = .0;
int lumen = 0;
void loop() {
if(Serial.available()) {
temp = analogRead(4) * .4882812 - 273.15;
lumen = analogRead(0);
Serial.print(temp);
Serial.print("|");
Serial.print(lumen);
Serial.println();
}
delay(10);
}
在 Raspberry 上,将运行以下脚本:
# run.py
#!/usr/bin/env python2
from arduino import Arduino
from poster import Poster
import time
import subprocess
import json
if __name__ == '__main__':
with open("config.json") as config_fh:
config = json.load(config_fh)
print(config)
base_url = config["URL"]
security_token = config["KEY"]
port = config["TTY"]
arduino = Arduino(port=port)
arduino.start()
time.sleep(1)
while True:
is_door_open = arduino.is_door_open()
temperature = arduino.get_temperature()
print arduino.is_door_open()
print arduino.get_temperature()
# nmap = subprocess.Popen("./networkClientsInNetwork.sh", stdout = subprocess.PIPE, stderr = subprocess.PIPE)
# network_clients_count = int(nmap.stdout.readlines()[0])
# print network_clients_count
# poster = Poster()
# poster.post_door_state(base_url, arduino.is_door_open(), security_token)
# poster.post_temperature(base_url, str(arduino.get_temperature()), security_token)
# poster.post_clients(base_url, str(network_clients_count), security_token)
time.sleep(3)
from threading import Thread
import serial
import random
import time
这是应该不断从串口获取值的线程:
class Arduino(Thread):
def __init__(self, port):
Thread.__init__(self, target=self.recieve)
self.daemon = True
self.last_recieved = None
self.serial = self.configure_port(port)
self.serial.open()
def configure_port(self, port_id):
ser = serial.Serial(port=port_id, timeout=1)
ser.rtscts = True
ser.dsrdtr = True
return ser
def recieve(self):
while True:
self.serial.flushInput()
self.serial.flushOutput()
if self.serial.isOpen():
self.last_recieved = self.serial.readline().replace("\r\n", "").split("|")
def getLastRecieved(self):
return self.last_recieved
def is_door_open(self):
try:
lumen = int(self.getLastRecieved()[1])
return_val = lumen > 150
except Exception:
return_val = None
pass
return return_val
def get_temperature(self):
try:
temperature = int(float(self.getLastRecieved()[0]))
temperature_offset = -5
return_val = int(temperature) + temperature_offset
except Exception:
return_val = None
pass
return return_val
现在,当我第一次启动run.py
时,它永远不会从串口获取数据。他们永远都是None
。
当我跑
ino serial
(开始picocom
)
并点击Enter,Arduino 将其所有数据发送到流中。如果我通过退出 picocomQ然后 start run.py
,python脚本可以从串口读取所有数据。
所以我想知道:我在初始化中缺少什么?如何使用picocom
via自动化串口初始化python
?