Bye Bye Moore

PoCソルジャーな零細事業主が作業メモを残すブログ

Raspberry Pi 3B+とRaspberry Pi Picoを連動させる その3:RasPi3B+側のI2C受信

実際のところ

3B+側

# Raspberry Pi 3B+ (Python)

import smbus
import time
import json
import sqlite3
import streamlit as st

# Setup I2C
bus = smbus.SMBus(1)

# Setup SQLite3
conn = sqlite3.connect('data.db')
c = conn.cursor()

# Create table
c.execute('''CREATE TABLE IF NOT EXISTS data
             (ID text, Value real, Timestamp text)''')

def get_data():
    data_json = bus.read_i2c_block_data(0x42, 0, 16)
    data_str = ''.join(chr(i) for i in data_json)
    data = json.loads(data_str)
    return data

def save_data(data):
    # Insert a row of data
    c.execute("INSERT INTO data VALUES (?, ?, ?)",
              (data['ID'], data['Value'], data['Timestamp']))
    # Save (commit) the changes
    conn.commit()

def display_data(data):
    st.write(f"ID: {data['ID']}")
    st.write(f"Value: {data['Value']}")
    st.write(f"Timestamp: {data['Timestamp']}")

while True:
    data = get_data()
    save_data(data)
    display_data(data)
    time.sleep(2)

# Close the connection if we are done
conn.close()