Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import board
- import busio
- import time
- import usb_cdc
- # I2C Setup (GP20 = SDA, GP21 = SCL)
- i2c = busio.I2C(board.GP21, board.GP20)
- device_address = 0x2a
- # USB Serial Output
- serial = usb_cdc.console
- # Function to read I2C data
- def read_i2c_data(register, num_bytes=2):
- """Reads data from a specific register on the I2C device."""
- try:
- buffer = bytearray(num_bytes) # Create a buffer for the received data
- i2c.writeto(device_address, bytes([register])) # Send register address (NO stop argument)
- i2c.readfrom_into(device_address, buffer) # Read the response
- return buffer
- except Exception as e:
- return f"Error: {e}"
- # Main loop
- while True:
- if not i2c.try_lock():
- continue
- try:
- raw_data = read_i2c_data(0x00) # Adjust register if needed
- if isinstance(raw_data, bytearray):
- data_value = int.from_bytes(raw_data, "big") # Convert to integer
- output_str = f"Sensor Data: {data_value}\n"
- else:
- output_str = raw_data # If it's an error message
- if serial and serial.connected:
- serial.write(output_str.encode())
- except Exception as e:
- serial.write(f"Read Error: {e}\n".encode())
- i2c.unlock()
- time.sleep(0.1) # Adjust polling rate as needed
Advertisement
Add Comment
Please, Sign In to add comment