RS485使用python读取温湿度并保存数据

import serial
import time
from openpyxl import Workbook
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

temp_send = '01 03 00 00 00 02 C4 0B'

ser = serial.Serial("COM4", 9600)

temp_send = bytes.fromhex(temp_send)
print(temp_send)

# Create a new workbook
wb = Workbook()
# Select the active sheet
ws = wb.active

# Write headers
ws.append(["date", "temperature", "humidity"])

# Lists to store the data
dates = []
temperatures = []
humidities = []

fig, ax = plt.subplots()


def update_chart(frame):
    if ser.is_open:
        print('port open ok')
        ser.write(temp_send)
        time.sleep(0.1)
        # 获取返回的缓冲data,获取的是buffer_data的长度    9
        buffer_data = ser.in_waiting
        # print(buffer_data, 'buffer_data')
        if buffer_data:
            # 返回的数据为2进制:b'\x01\x03\x04\x01\x08\x022\xfa\xb8'
            return_data = ser.read(buffer_data)
            # print('返回的数据2进制:', return_data)
            # 二进制转换为16进制:010304010802307b79
            return_data_hex = str(return_data.hex())
            print('返回的数据转换为16进制:', return_data_hex)

            # 对返回的数据进行解析,获取温度和湿度数据
            humidity = int(return_data_hex[6:10], 16) / 10
            temperature = int(return_data_hex[10:14], 16) / 10

            # Get current date
            current_date = time.strftime("%Y/%m/%d %H%M")

            # Write data to Excel
            ws.append([current_date, temperature, humidity])

            # Append data to lists
            dates.append(current_date)
            temperatures.append(temperature)
            humidities.append(humidity)

            # Save the workbook
            wb.save('0.xlsx')

            print("当前湿度为:", humidity)
            print("当前温度为:", temperature)

            # Clear the plot
            ax.clear()

            # Plot the data
            ax.plot(dates, temperatures, label='Temperature')
            ax.plot(dates, humidities, label='Humidity')
            ax.set_xlabel('Date')
            ax.set_ylabel('Value')
            ax.set_title('Temperature and Humidity Data')
            ax.legend()
            plt.xticks(rotation=45)
            plt.tight_layout()


# Update the chart every 1 second
ani = FuncAnimation(fig, update_chart, interval=1000)

plt.show()

你可能感兴趣的:(python)