Python读取arduino数据并实时绘图

我使用arduino uno 与 ds18b20。

python编写串口代码与数据显示

绘图使用matplotlib库

Python读取arduino数据并实时绘图_第1张图片

Arduino代码

DallasTemperature 下载地址  

https://www.arduino.cn/thread-82352-1-1.html

#include 
#include 

// 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);
}

 

Python代码

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")

 

你可能感兴趣的:(Arduino)