樹莓派查詢串口python
ls /dev/tty*
經過 拔插發現多了一個緩存
就是他了。oop
arudnio代碼測試
void setup() { Serial.begin(9600); //打開串口 } void loop() { Serial.println("Hello Raspberry,I am Arduino."); delay(1000); if ( Serial.available()) { if('s' == Serial.read()) Serial.println("Hello Raspberry,I am Arduino."); } }
# -*- coding: utf-8 -* import serial import time ser = serial.Serial('/dev/ttyUSB0', 9600) if ser.isOpen == False: ser.open() # 打開串口 ser.write(b"Raspberry pi is ready") try: while True: size = ser.inWaiting() # 得到緩衝區字符 if size != 0: response = ser.read(size) # 讀取內容並顯示 print(response) ser.flushInput() # 清空接收緩存區 time.sleep(0.1) # 軟件延時 except KeyboardInterrupt: ser.close()
#include <DHT.h> #define DHTPIN 3 #define DHTTYPE DHT11 DHT dht(DHTPIN, DHTTYPE); void setup() { // put your setup code here, to run once: Serial.begin(9600); dht.begin(); Serial.println("Hi Vcancy. Arduino is running..."); } /** Arduino loop @param none @return none */ char target[] = "GET TH"; void loop() { // 每次等待2秒後再輸出(這裏必須等大於1秒,否則不許確) delay(2000); // 從串口讀數據並判斷 if (Serial.available() > 0) { if ( Serial.find(target)) { // 獲取溫度或者溼度須要250毫秒! // 傳感器獲取到的溫度和溼度多是2秒內的 float h = dht.readHumidity();// 讀取當前的溼度 float t = dht.readTemperature(); // 讀取當前的溫度,單位C float f = dht.readTemperature(true);//讀取當前的溫度,單位F // 若是讀取失敗則退出,再讀取一次 if (isnan(h) || isnan(t) || isnan(f)) { Serial.println("Failed to read from DHT sensor!"); return; } // 讀取體感溫度,單位F float hif = dht.computeHeatIndex(f, h); // 讀取體感溫度,單位C float hic = dht.computeHeatIndex(t, h, false); Serial.print("溼度: "); Serial.print(h); Serial.print(" %\t"); Serial.print("溫度: "); Serial.print(t); Serial.print(" *C "); Serial.print(f); Serial.print(" *F\t"); Serial.print("體感溫度: "); Serial.print(hic); Serial.print(" *C "); Serial.print(hif); Serial.println(" *F"); } } }
而後能夠在串口助手中進行測試,我這裏由於項目須要,將GET TH 改成了數字8,而且修改了一下輸出,下面大家能夠看到我作的更改,應該更符合同窗們對數據處理的要求,這裏大家在測試時仍然能夠輸入GET TH進行測試:ui
須要先安裝python串口讀取的庫文件:pip install pyserial
(若是已經安裝過了則忽略)
找到Arduino的串口地址:/dev/ttyACM0
code
import serial ser = serial.Serial('/dev/ttyACM0', 9600, timeout=1) try: while 1: ser.write(b"GET TH") response = str(ser.readline().decode()) if response.startswith('溼度:'): print(response.strip('\n')) except KeyboardInterrupt: ser.close()
若是要單截取採集到的溫溼度,對數據進行處理,而不須要打印全部信息,咱們能夠在python和Arduino作以下更改:blog
首先在Arduino中,咱們不須要像串口打印那麼多數據,只取咱們須要的溫溼度,像這樣(效果同上面的GIF):ip
Serial.print("hum: "); Serial.print(h); Serial.print("tem: "); Serial.println(t); // 打印出效果以下:hum: 33.0tem: 25.00
而後在python中,咱們經過字符串截取,取到咱們的溫溼度,這裏咱們截取兩位整數utf-8
response = str(single.readline().decode()) if response.startswith('hum:'): #截取整數部分 hum = response[5:7] #33 tem = response[-6:-3] # 25 # 將處理後的數據放在templateData 中 templateData = { 'tem': tem, 'hum': hum } print(response.strip('\n'))