2017-06-21 1222 views
0

我想通過串行將數據從arduino發送到計算機。然後我想記錄基於當前時間戳的時間,並將其保存在txt文件中。我該怎麼辦?你的建議對我非常有用。從arduino讀取數據並添加時間戳

上的Arduino這是我的代碼:

#include <DHT.h> 

#define DHTPIN 2 
#define DHTTYPE DHT11 

DHT dht(DHTPIN, DHTTYPE); 

void setup(){ 
    Serial.begin(9600); 
    dht.begin(); 
} 
void loop(){ 
    float hum = dht.readHumidity(); 
    float temp= dht.readTemperature(); 

    Serial.print("Humidity: "); 
    Serial.print(hum); 
    Serial.print(" %, Temp: "); 
    Serial.print(temp); 
    Serial.println(" Celsius"); 
    delay(2000); 
} 
+1

你接收數據通過串行端口在電腦上?你的Python代碼在哪裏讀取? – stevieb

回答

1

您可以使用此python腳本作爲您的接收器代碼。 用你的Arduino端口改變'port'。

不要忘記下載序列庫,如果它丟失:https://pypi.python.org/pypi/pyserial

import serial 
import time 
import datetime 

ser = serial.Serial(
    port='COM5',\ 
    baudrate=9600,\ 
    parity=serial.PARITY_NONE,\ 
    stopbits=serial.STOPBITS_ONE,\ 
    bytesize=serial.EIGHTBITS,\ 
     timeout=0) 

print("connected to: " + ser.portstr) 

while True: 
    line = ser.readline() 
    timestamp = str(time.time()) 
    #timestamp = str(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')) 
    with open('output.txt', 'a') as pyfile: 
     pyfile.write(line + ' ' + timestamp +'\n') 

ser.close()