This Python code demonstrates how to use bitwise operators to control LEDs in an embedded system. It defines LEDs as individual bits and uses bitwise operations to turn them on and off.
# filepath: g:\2025miura\88we100windows11\WEPY200bookcopilot\sample35.py
# Filename: WEPY200/sample35.py 20250501
# Description: Python sample code for Bitwise operators for beginners in embedded technology
# machine: VIVO book ASUS windows11
# Language: Python 3.10.6
# IDE: VS code with Copilot Gemini Flash
# python sample35.py
# Bitwise operators: & (AND), | (OR), ^ (XOR), ~ (NOT), << (Left Shift), >> (Right Shift)
# Example: Controlling LEDs
# Let's represent the state of LEDs using bits
LED1 = 0b00000001 # First LED
LED2 = 0b00000010 # Second LED
LED3 = 0b00000100 # Third LED
print('leds_initial')
print(f'{{"LED1":{LED1:08b}}}')
print(f'{{"LED2":{LED2:08b}}}')
print(f'{{"LED3":{LED3:08b}}}')
# Initial state: All LEDs are off
print(f'{{leds_status}}')
led_status = 0b00000000
print(f'{{"leds_status":,{led_status:08b}}}')
# Turn on LED1
led_status = led_status | LED1 # OR operation
#print(f"Turn on LED1: {led_status:08b}") # Output: 00000001
print(f'turn on LED1: {{"leds_status":,{led_status:08b}}}')
# Turn on LED2
led_status = led_status | LED2 # OR operation
#print(f"Turn on LED2: {led_status:08b}") # Output: 00000011
print(f'turn on LED2: {{"leds_status":,{led_status:08b}}}')
# Turn off LED1
led_status = led_status & ~LED1 # AND and NOT operation
#print(f"Turn off LED1: {led_status:08b}") # Output: 00000010
print(f'turn off LED1: {{"leds_status":,{led_status:08b}}}')
#print(f'turn on LED2: {{"leds_status":,{led_status:08b}}}')
# Invert the state of all LEDs
#led_status = ~led_status & 0xFF # NOT operation (limited to 8 bits)
# Check if LED3 is on
if led_status & LED3: # AND operation
print("LED3_status is ON")
else:
print("LED3_status is OFF")
# Example of Left Shift and Right Shift
print("--------------------")
value = 0b00000001 # 1
print(f'{{"bit_value":{value:08b}}}')
# Shift left by 2 bits
shifted_left = value << 2
print(f'shifted left by 2:{{"bit_value":{shifted_left:08b}}}')
#print(f"Shifted left by 2: {shifted_left:08b}") # Output: 00000100 (4)
# Shift right by 1 bit
shifted_right = shifted_left >> 1
print(f'Shifted right by 1:{{"bit_value":{shifted_right:08b}}}')
This code is a good introduction to using bitwise operators for LED control in embedded systems. The code is well-commented and easy to follow. By adding functions, error handling, and exploring more complex operations, the code can be further improved.