1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| class SPIConfig(ctypes.Structure): _fields_ = [ ("iMode", ctypes.c_ubyte), ("iClock", ctypes.c_ubyte), ("iByteOrder", ctypes.c_ubyte), ("iSpiWriteReadInterval", ctypes.c_ushort), ("iSpiOutDefaultData", ctypes.c_ubyte), ("iChipSelect", ctypes.c_ulong), ("CS1Polarity", ctypes.c_ubyte), ("CS2Polarity", ctypes.c_ubyte), ("iIsAutoDeativeCS", ctypes.c_ushort), ("iActiveDelay", ctypes.c_ushort), ("iDelayDeactive", ctypes.c_ulong) ]
def spi_init(self, device_index: int, spi_config: SPIConfig) -> bool: """ Initialize the SPI Controller.
Args: device_index (int): The device number. spi_config (SPIConfig): The configuration for the SPI controller.
Returns: bool: True if initialization is successful, False otherwise. """ result = self.ch347dll.CH347SPI_Init(device_index, ctypes.byref(spi_config)) return result
def spi_write(self, device_index: int, chip_select: int, write_data: bytes, write_step: int = 512) -> bool: """ SPI write data.
Args: device_index (int): Device number. chip_select (int): Chip selection control. When bit 7 is 0, chip selection control is ignored. When bit 7 is 1, chip selection operation is performed. write_data (bytes): Data to write. write_step (int, optional): The length of a single block to be read. Default is 512.
Returns: bool: True if successful, False otherwise. """ write_length = len(write_data) write_buffer = ctypes.create_string_buffer(write_data) result = self.ch347dll.CH347SPI_Write(device_index, chip_select, write_length, write_step, write_buffer) return result
def spi_read(self, device_index: int, chip_select: int, write_data: bytes, read_length: int) -> bytes: """ SPI read data.
Args: device_index (int): Device number. chip_select (int): Chip selection control. When bit 7 is 0, chip selection control is ignored. When bit 7 is 1, chip selection operation is performed. write_data (bytes): Data to write. read_length (int): Number of bytes to read.
Returns: bytes: Data read in from the SPI stream if successful, None otherwise. """ write_length = len(write_data)
write_buffer = ctypes.create_string_buffer(write_data)
read_buffer = ctypes.create_string_buffer(read_length)
combined_buffer = ctypes.create_string_buffer(write_buffer.raw[:write_length] + read_buffer.raw)
result = self.ch347dll.CH347SPI_Read(device_index, chip_select, write_length, ctypes.byref(ctypes.c_ulong(read_length)), combined_buffer)
if result: read_data = combined_buffer[:read_length] return bytes(read_data) else: return None
|