Guest User

Frhulst eddy code

a guest
Mar 6th, 2025
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | Source Code | 0 0
  1. import board
  2. import busio
  3. import time
  4. import usb_cdc
  5.  
  6. # I2C Setup (GP20 = SDA, GP21 = SCL)
  7. i2c = busio.I2C(board.GP21, board.GP20)
  8. device_address = 0x2a
  9.  
  10. # USB Serial Output
  11. serial = usb_cdc.console
  12.  
  13. # Function to read I2C data
  14. def read_i2c_data(register, num_bytes=2):
  15. """Reads data from a specific register on the I2C device."""
  16. try:
  17. buffer = bytearray(num_bytes) # Create a buffer for the received data
  18. i2c.writeto(device_address, bytes([register])) # Send register address (NO stop argument)
  19. i2c.readfrom_into(device_address, buffer) # Read the response
  20. return buffer
  21. except Exception as e:
  22. return f"Error: {e}"
  23.  
  24. # Main loop
  25. while True:
  26. if not i2c.try_lock():
  27. continue
  28. try:
  29. raw_data = read_i2c_data(0x00) # Adjust register if needed
  30. if isinstance(raw_data, bytearray):
  31. data_value = int.from_bytes(raw_data, "big") # Convert to integer
  32. output_str = f"Sensor Data: {data_value}\n"
  33. else:
  34. output_str = raw_data # If it's an error message
  35.  
  36. if serial and serial.connected:
  37. serial.write(output_str.encode())
  38.  
  39. except Exception as e:
  40. serial.write(f"Read Error: {e}\n".encode())
  41.  
  42. i2c.unlock()
  43. time.sleep(0.1) # Adjust polling rate as needed
  44.  
  45.  
Advertisement
Add Comment
Please, Sign In to add comment