#!/usr/bin/env python3 """ BPIO2 SPI Example - Read flash memory JEDEC ID Demonstrates basic SPI communication with flash memory devices. """ import argparse import sys # Import BPIO client and SPI interface from pybpio.bpio_client import BPIOClient from pybpio.bpio_spi import BPIOSPI def spi_read_jedec_id(client, speed=1000000): """Read JEDEC ID from SPI flash memory.""" spi = BPIOSPI(client) if spi.configure( speed=speed, clock_polarity=False, clock_phase=False, chip_select_idle=True, psu_enable=True, psu_set_mv=3300, psu_set_ma=0, pullup_enable=False, ): try: print(f"SPI configured at {speed/1000000:.1f}MHz") # MINIMALLY ... must set BPIO2 high (/HOLD) # Probably SHOULD set BPIO3 low (/WP) if True: print(f"Setting BPIO2 as output/high") BPIO2_MASK = 0b00000100 spi.set_io_direction(BPIO2_MASK, 1) spi.set_io_value(BPIO2_MASK, 1) else: print(f"Setting BPIO3..0 as HHLH") BPIO_HIGH_MASK = 0b00001101 BPIO_LOW_MASK = 0b00000010 spi.set_io_direction(BPIO_HIGH_MASK, 1) spi.set_io_value(BPIO_HIGH_MASK, 1) spi.set_io_direction(BPIO_LOW_MASK, 1) spi.set_io_value(BPIO_LOW_MASK, 0) except Exception as e: print(f"Error during JEDEC probe: {e}") print(f"Stack trace:") import traceback traceback.print_exc() return False return True else: print("Failed to configure SPI interface") return False def main(): parser = argparse.ArgumentParser( description='BPIO2 SPI Test - Set HOLD (BPIO2) high, so can communicate with SPI flash memory', formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Examples: %(prog)s -p COM3 # Read JEDEC ID at 1MHz %(prog)s -p COM3 --speed 10000000 # Read JEDEC ID at 10MHz """ ) parser.add_argument('-p', '--port', required=True, help='Serial port (e.g., COM3, /dev/ttyUSB0)') parser.add_argument('--speed', type=int, default=1000000, help='SPI clock speed in Hz (default: 1000000)') args = parser.parse_args() try: client = BPIOClient(args.port) print(f"Connected to Bus Pirate on {args.port}") success = spi_read_jedec_id(client, args.speed) client.close() return 0 if success else 1 except Exception as e: print(f"Error: {e}") return 1 if __name__ == '__main__': sys.exit(main())