【发布时间】:2021-07-13 19:11:56
【问题描述】:
我很困惑您如何设置代码以将三个单独的读数读取到 python 中的 matplotlib 图形中,以及 Python 和 Arduino 代码之间的时序。
Arduino 代码
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_INA260.h>
Adafruit_INA260 ina260 = Adafruit_INA260();
void setup() {
Serial.begin(115200);
// Wait until serial port is opened
while (!Serial) { delay(10); }
// Serial.println("Adafruit INA260 Test");
if (!ina260.begin()) {
//Serial.println("Couldn't find INA260 chip");
while (1);
}
//Serial.println("Found INA260 chip");
}
void loop() {
//Serial.print("Current: ");
Serial.println(ina260.readCurrent());
// Serial.println(" mA");
// Serial.print("Bus Voltage: ");
Serial.println(ina260.readBusVoltage());
// Serial.println(" mV");
// Serial.print("Power: ");
Serial.println(ina260.readPower());
// Serial.println(" mW");
delay(1000);
}
Python 代码
import serial
import time
import glob
import csv
import matplotlib
matplotlib.use("tkAgg")
import matplotlib.pyplot as plt
import numpy as np
ser = serial.Serial('/dev/ttyUSB0', baudrate = 115200, timeout = 5)
ser.flushInput()
plot_window = 20
y_current = np.array(np.zeros([plot_window]))
y_voltage = np.array(np.zeros([plot_window]))
y_power = np.array(np.zeros([plot_window]))
plt.ion()
fig, (ax1, ax2, ax3) = plt.subplots(3)
lineC, = ax1.plot(y_current)
lineV, = ax2.plot(y_voltage)
lineP, = ax3.plot(y_power)
while True:
try:
current_bytes = ser.readline()
voltage_bytes = ser.readline()
power_bytes = ser.readline()
try:
decoded_current = float(current_bytes[0:len(current_bytes)-2].decode("utf-8").rstrip())
decoded_voltage = float(voltage_bytes[0:len(voltage_bytes)-2].decode("utf-8").rstrip())
decoded_power = float(power_bytes[0:len(power_bytes)-2].decode("utf-8").rstrip())
print(decoded_current + " mA " + decoded_voltage + " mV " + decoded_power + " mW ")
except:
continue
# with open("test_data.csv","a") as f:
# writer = csv.writer(f,delimiter=",")
# writer.writerow([time.time(),decoded_bytes])
y_current = np.append(y_current,decoded_current)
y_current = y_current[1:plot_window+1]
lineC.set_ydata(y_current)
y_voltage = np.append(y_voltage,decoded_voltage)
y_voltage = y_voltage[1:plot_window+1]
lineV.set_ydata(y_voltage)
y_power = np.append(y_power,decoded_power)
y_power= y_power[1:plot_window+1]
lineP.set_ydata(y_power)
ax1.relim()
ax1.autoscale_view()
ax2.relim()
ax2.autoscale_view()
ax3.relim()
ax3.autoscale_view()
fig.canvas.draw()
fig.canvas.flush_events()
except:
print("Keyboard Interrupt")
break
如果我只跟踪一个单一的功率测量,我可以让 python 代码成功绘制数据,我只是不确定如何为多个数据读数做这件事。
【问题讨论】:
标签: python numpy matplotlib arduino