Skip to content

Instantly share code, notes, and snippets.

@FLamparski FLamparski/plot.py

Created Jun 5, 2019
Embed
What would you like to do?
Example programs for the SDS-011
import serial
import struct
from collections import deque
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as anim
from matplotlib.ticker import FuncFormatter
# Change this to the right port - /dev/tty* on Linux and Mac and COM* on Windows
PORT = 'COM5'
MAX_LENGTH = 60
UNPACK_PAT = '<ccHHHcc'
pm25_history = deque(np.zeros(MAX_LENGTH), maxlen=MAX_LENGTH)
pm10_history = deque(np.zeros(MAX_LENGTH), maxlen=MAX_LENGTH)
x = np.arange(0, MAX_LENGTH)
fig, ax = plt.subplots()
ax.set_ylim(0, 15)
ax.set_xlim(0, MAX_LENGTH - 1)
line_pm25, = ax.plot(x, np.zeros(MAX_LENGTH), color='r')
line_pm10, = ax.plot(x, np.zeros(MAX_LENGTH), color='b')
ax.xaxis.set_major_formatter(FuncFormatter(lambda x, pos: '{:.0f}s'.format(MAX_LENGTH - x - 1)))
plt.title('PM2.5/PM10')
ser = serial.Serial(PORT, 9600, bytesize=8, parity='N', stopbits=1)
def init():
return line_pm25, line_pm10
def animate(i):
packet = ser.read(10)
unpacked = struct.unpack(UNPACK_PAT, packet)
pm25 = unpacked[2] / 10.0
pm10 = unpacked[3] / 10.0
pm25_history.append(pm25)
pm10_history.append(pm10)
line_pm25.set_ydata(pm25_history)
line_pm10.set_ydata(pm10_history)
return line_pm25, line_pm10
animation = anim.FuncAnimation(fig, animate, init_func=init, interval=1000, blit=True)
plt.show()
import serial
import struct
from datetime import datetime
# Change this to the right port - /dev/tty* on Linux and Mac and COM* on Windows
PORT = 'COM5'
UNPACK_PAT = '<ccHHHcc'
with serial.Serial(PORT, 9600, bytesize=8, parity='N', stopbits=1) as ser:
while True:
data = ser.read(10)
unpacked = struct.unpack(UNPACK_PAT, data)
ts = datetime.now()
pm25 = unpacked[2] / 10.0
pm10 = unpacked[3] / 10.0
print("{}: PM 2.5 = {}, PM 10 = {}".format(ts, pm25, pm10))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.