Last active
February 11, 2025 09:34
-
-
Save ensarkarabudak/57e47cc6ab08b29cadcadd8989a0002f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import smbus2 as smbus | |
| import time | |
| # Initialize the I2C bus | |
| bus = smbus.SMBus(1) | |
| dev_addr = 0x20 # Address of the TCA6408A | |
| conf_addr = 0x03 # Address to configure the pins | |
| write_addr = 0x01 # Address to write data to the pins | |
| # Function to set the LED color | |
| def set_led_color(red, green, blue): | |
| """ | |
| Set the color of the RGB LED. | |
| :param red: Red component (0: on, 1: off) | |
| :param green: Green component (0: on, 1: off) | |
| :param blue: Blue component (0: on, 1: off) | |
| """ | |
| # read the current state | |
| led_state = bus.read_byte_data(dev_addr, 0x0) | |
| # set each bit appropriately | |
| # P2 -> Red (bit 2) | |
| # P3 -> Green (bit 3) | |
| # P4 -> Blue (bit 4) | |
| for p,v in zip([2,3,4],[red,green,blue]): | |
| led_state = led_state | (1<<p) if v == 1 else led_state & ~(1<<p) | |
| # Write the state to the TCA6408A | |
| bus.write_byte_data(dev_addr, write_addr, led_state) | |
| # Configure the pins as outputs | |
| conf_data = 0x00 # All pins are set as outputs | |
| bus.write_byte_data(dev_addr, conf_addr, conf_data) | |
| try: | |
| while True: | |
| # Turn the LED red | |
| set_led_color(0, 1, 1) | |
| print("LED: Red") | |
| time.sleep(1) | |
| # Turn the LED green | |
| set_led_color(1, 0, 1) | |
| print("LED: Green") | |
| time.sleep(1) | |
| # Turn the LED blue | |
| set_led_color(1, 1, 0) | |
| print("LED: Blue") | |
| time.sleep(1) | |
| # Turn the LED off | |
| set_led_color(1, 1, 1) | |
| print("LED: Off") | |
| time.sleep(1) | |
| except KeyboardInterrupt: | |
| # Turn the LED off when the program is stopped | |
| set_led_color(1, 1, 1) | |
| print("Program stopped.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment