Untitled
unknown
plain_text
5 months ago
4.0 kB
4
Indexable
// Raspberry Pi Side # spi_master.py import spidev import time import RPi.GPIO as GPIO class GPIOController: def __init__(self): self.spi = spidev.SpiDev() self.spi.open(0, 0) # Bus 0, Device 0 self.spi.max_speed_hz = 1000000 self.spi.mode = 0 # Command definitions self.CMD_SET_HIGH = 0x01 self.CMD_SET_LOW = 0x02 self.CMD_READ = 0x03 # Response codes self.RESP_SUCCESS_HIGH = 0xAA self.RESP_SUCCESS_LOW = 0xBB self.RESP_ERROR = 0xFF def gpio_control(self, command, gpio_num): """ Send command to control specific GPIO Returns: Response from STM32 """ if not 0 <= gpio_num <= 7: raise ValueError("GPIO number must be between 0 and 7") response = self.spi.xfer2([command, gpio_num]) return response[1] def set_gpio_high(self, gpio_num): """Set specific GPIO HIGH""" response = self.gpio_control(self.CMD_SET_HIGH, gpio_num) success = response == self.RESP_SUCCESS_HIGH if not success: print(f"Error setting GPIO {gpio_num} HIGH (Response: 0x{response:02X})") return success def set_gpio_low(self, gpio_num): """Set specific GPIO LOW""" response = self.gpio_control(self.CMD_SET_LOW, gpio_num) success = response == self.RESP_SUCCESS_LOW if not success: print(f"Error setting GPIO {gpio_num} LOW (Response: 0x{response:02X})") return success def read_gpio(self, gpio_num): """Read state of specific GPIO""" response = self.gpio_control(self.CMD_READ, gpio_num) if response not in [0, 1]: print(f"Error reading GPIO {gpio_num} (Response: 0x{response:02X})") return None return response def cleanup(self): """Clean up SPI resources""" self.spi.close() def run_test_sequence(): """Run a test sequence to verify all GPIOs""" controller = GPIOController() try: print("Starting GPIO test sequence...") # Test 1: Set each GPIO HIGH in sequence print("\nTest 1: Setting GPIOs HIGH sequentially") for gpio in range(8): if controller.set_gpio_high(gpio): print(f"Set GPIO {gpio} HIGH - Success") time.sleep(0.5) time.sleep(2) # Test 2: Set each GPIO LOW in sequence print("\nTest 2: Setting GPIOs LOW sequentially") for gpio in range(8): if controller.set_gpio_low(gpio): print(f"Set GPIO {gpio} LOW - Success") time.sleep(0.5) # Test 3: Read all GPIO states print("\nTest 3: Reading all GPIO states") for gpio in range(8): state = controller.read_gpio(gpio) if state is not None: print(f"GPIO {gpio} state: {'HIGH' if state else 'LOW'}") # Test 4: Alternating pattern print("\nTest 4: Creating alternating pattern") for gpio in range(8): if gpio % 2 == 0: controller.set_gpio_high(gpio) else: controller.set_gpio_low(gpio) time.sleep(2) # Test 5: Binary counter print("\nTest 5: Binary counter (8 counts)") for count in range(8): for gpio in range(8): if count & (1 << gpio): controller.set_gpio_high(gpio) else: controller.set_gpio_low(gpio) time.sleep(1) except KeyboardInterrupt: print("\nTest sequence interrupted by user") finally: # Set all GPIOs LOW before exit print("\nCleaning up...") for gpio in range
Editor is loading...
Leave a Comment