本帖最后由 11066 于 2018-10-25 19:18 编辑
我使用arduino uno 与 ds18b20。
python编写串口代码与数据显示
地址
https://blog.csdn.net/qq_39020934/article/details/83348972
绘图使用matplotlib库
Arduino代码
[pre]#include <OneWire.h>
#include <DallasTemperature.h>
// Data wire is plugged into pin 2 on the Arduino
#define ONE_WIRE_BUS 2
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);
void setup(void)
{
Serial.begin(9600); //Begin serial communication
Serial.println("Arduino Digital Temperature // Serial Monitor Version"); //Print a message
sensors.begin();
}
void loop(void)
{
// Send the command to get temperatures
sensors.requestTemperatures();
Serial.print("Temperature is: ");
Serial.println(sensors.getTempCByIndex(0)); // Why "byIndex"? You can have more than one IC on the same bus. 0 refers to the first IC on the wire
//Update value every 1 sec.
delay(1000);
}[/pre]
Python代码
[pre]import serial
import matplotlib.pyplot as plt
from drawnow import *
import atexit
import time
values = []
plt.ion()#打开交互模式
serialArduino = serial.Serial('COM14', 9600)
def plotValues():
plt.title('Serial temperature from Arduino')
plt.grid(True)
plt.ylabel('temperature')
plt.plot(values,'rx-', label='temperature')
plt.legend(loc='upper right')
def doAtExit():
serialArduino.close()
print("Close serial")
print("serialArduino.isOpen() = " + str(serialArduino.isOpen()))
atexit.register(doAtExit)#程序退出时,回调函数
print("serialArduino.isOpen() = " + str(serialArduino.isOpen()))
#预加载虚拟数据
for i in range(0,50):
values.append(0)
while True:
while (serialArduino.inWaiting()==0):
pass
print("readline()")
valueRead = serialArduino.readline(500)
#检查是否可以输入有效值
try:
valueInInt = float(valueRead)
print(valueInInt)
if valueInInt <= 1024:
if valueInInt >= 0:
values.append(valueInInt)
values.pop(0)
drawnow(plotValues)
else:
print("Invalid! negative number")#无效 负数
else:
print("Invalid! too large")# 无效 超过1024
except ValueError:
print("Invalid! cannot cast")[/pre]
DallasTemperature.zip
(29.23 KB, 下载次数: 143)
|