1+ from sys import exit
2+ from machine import I2C
3+ from time import sleep
4+
5+ pinstrap_map = {
6+ 0x3C : "BUZZER" ,
7+ 0x7C : "BUTTONS" ,
8+ 0x76 : "ENCODER" ,
9+ 0x74 : "ENCODER" ,
10+ 0x6C : "SMARTLEDS"
11+ }
12+
13+ def pinstrap_to_name (address ):
14+ if address in pinstrap_map :
15+ return pinstrap_map [address ]
16+ return "UNKNOWN"
17+
18+ bus = I2C (0 )
19+ devices_on_bus = bus .scan ()
20+
21+ print ()
22+
23+ if len (devices_on_bus ) == 0 :
24+ print ("No devices found on the bus. Try resetting the board." )
25+ exit (1 )
26+
27+ print ("The following devices were found on the bus:" )
28+
29+ for index , device_address in enumerate (devices_on_bus ):
30+ pinstrap_address = bus .readfrom (device_address , 1 )
31+ device_name = pinstrap_to_name (pinstrap_address [0 ])
32+ print (f"{ index + 1 } ) { device_name } at { hex (device_address )} " )
33+
34+ choice = int (input ("\n Enter the device number for which you want to change the address: " ))
35+ if choice < 1 or choice > len (devices_on_bus ):
36+ print ("Invalid choice. Please select a valid device number." )
37+ exit (1 )
38+
39+ selected_device_address = devices_on_bus [choice - 1 ]
40+
41+ # Read address from user input
42+ new_address = int (input ("Enter the new address (hexadecimal or decimal): " ), 0 )
43+
44+ if new_address < 0 or new_address > 127 :
45+ print ("Invalid address. Address must be between 0 and 127" )
46+ exit (1 )
47+
48+ print (f"Changing address of device at { hex (selected_device_address )} to { hex (new_address )} ..." )
49+
50+ data = bytearray (40 )
51+ # Set the first two bytes to 'C' and 'F' followed by the new address
52+ data [0 :2 ] = b'CF'
53+ data [2 ] = new_address * 2
54+
55+ try :
56+ bus .writeto (selected_device_address , data )
57+ except OSError :
58+ pass # Device resets immediately and causes ENODEV to be thrown which is expected
59+ sleep (1 )
60+
61+ # Check if the address was successfully changed
62+ devices_on_bus = bus .scan ()
63+ if new_address in devices_on_bus :
64+ print (f"✅ Address changed successfully to { hex (new_address )} " )
65+ else :
66+ print ("❌ Failed to change address. Please try again." )
0 commit comments