SPI read and write

  1'''
  2SPI - SPI_read_and_write.py with asynchronous mode.
  3
  4This example demonstrates how to communicate with USBDAQF1AD (master) and 25LC640 (slave) with SPI interface.
  5
  6First, it shows how to open SPI port & DIO pins and configure SPI parameters.
  7Second, write some bytes with address into EEPROM (25LC640). We have to make sure that bytes written in address is correct however read address from EEPROM (25LC640).
  8Last, close SPI port & DIO pins.
  9
 10-------------------------------------------------------------------------------------
 11Please change correct serial number or IP and port number BEFORE you run example code.
 12
 13For other examples please check:
 14    https://github.com/WPC-Systems-Ltd/WPC_Python_driver_release/tree/main/examples
 15See README.md file to get detailed usage of this example.
 16
 17Copyright (c) 2022-2025 WPC Systems Ltd. All rights reserved.
 18'''
 19
 20## WPC
 21from wpcsys import pywpc
 22
 23## Python
 24import asyncio
 25import sys
 26sys.path.insert(0, 'src/')
 27
 28
 29async def main():
 30    ## Get Python driver version
 31    print(f'{pywpc.PKG_FULL_NAME} - Version {pywpc.__version__}')
 32
 33    ## Create device handle
 34    dev = pywpc.USBDAQF1AD()
 35
 36    ## Connect to device
 37    try:
 38        dev.connect("default")  ## Depend on your device
 39    except Exception as err:
 40        pywpc.printGenericError(err)
 41        ## Release device handle
 42        dev.close()
 43        return
 44
 45    try:
 46        '''
 47        Take 25LC640 for example
 48        '''
 49
 50        ## Parameters setting
 51        port = 2  ## Depend on your device
 52        datasize = 0  ## Mode: 0 = 8-bit data, 1 = 16-bit data.
 53        first_bit = 0  ## Mode: 0 = MSB first, 1 = LSB first.
 54        prescaler = 64
 55        mode = 0  ## 0 : CPOL = 0 CPHA = 0, 1 : CPOL = 0 CPHA = 1, 2 : CPOL = 1 CPHA = 0, 3 : CPOL = 1 CPHA = 1
 56
 57        if port == 1:
 58            DO_port = 2
 59            DO_index = [0]  ## CS pin
 60
 61        elif port == 2:
 62            DO_port = 3
 63            DO_index = [2]  ## CS pin
 64
 65        ## Generate random data
 66        import numpy as np
 67        addr = np.random.randint(8)  ## Generate a random address
 68        value = np.random.randint(256)  ## Generate a random value
 69
 70        WRITE = 0x02
 71        DUMMY = 0x01
 72        READ = 0x03
 73        WREN = 0x06
 74
 75        ## Get firmware model & version
 76        driver_info = await dev.Sys_getDriverInfo_async()
 77        print(f"Model name: {driver_info[0]}, Firmware version: {driver_info[-1]} ")
 78
 79        '''
 80        Open DO pins & SPI port & set CS(pin0) to high
 81        '''
 82
 83        ## Open pin0 with digital output
 84        err = await dev.DO_openPins_async(DO_port, DO_index)
 85        print(f"DO_openPins_async in port {DO_port}, status: {err}")
 86
 87        ## Open SPI
 88        err = await dev.SPI_open_async(port)
 89        print(f"SPI_open_async in port {port}, status: {err}")
 90
 91        ## Set CS(pin0) to high
 92        err = await dev.DO_writePins_async(DO_port, DO_index, [1])
 93        print(f"DO_writePins_async in port {DO_port}, status: {err}")
 94
 95        '''
 96        Set SPI parameter
 97        '''
 98
 99        ## Set SPI port and set datasize to 8-bits data
100        err = await dev.SPI_setDataSize_async(port, datasize)
101        print(f"SPI_setDataSize_async in port {port}, status: {err}")
102
103        ## Set SPI port and set first_bit to MSB first
104        err = await dev.SPI_setFirstBit_async(port, first_bit)
105        print(f"SPI_setFirstBit_async in port {port}, status: {err}")
106
107        ## Set SPI port and set prescaler to 64
108        err = await dev.SPI_setPrescaler_async(port, prescaler)
109        print(f"SPI_setPrescaler_async in port {port}, status: {err}")
110
111        ## Set SPI port and set CPOL and CPHA to 0 (mode 0)
112        err = await dev.SPI_setMode_async(port, mode)
113        print(f"SPI_setMode_async in port {port}, status: {err}")
114
115        '''
116        Write data via SPI
117        '''
118
119        ## Set CS(pin0) to low
120        err = await dev.DO_writePins_async(DO_port, DO_index, [0])
121        print(f"DO_writePins_async in port {DO_port}, status: {err}")
122
123        ## Write WREN byte
124        err = await dev.SPI_write_async(port, [WREN])
125        print(f"SPI_write_async in port {port}, status: {err}")
126
127        ## Set CS(pin0) to high
128        err = await dev.DO_writePins_async(DO_port, DO_index, [1])
129        print(f"DO_writePins_async in port {DO_port}, status: {err}")
130
131        '''
132        Write data via SPI
133        '''
134
135        ## Set CS(pin0) to low
136        err = await dev.DO_writePins_async(DO_port, DO_index, [0])
137        print(f"DO_writePins_async in port {DO_port}, status: {err}")
138
139        ## Write the generated byte into the generated address
140        err = await dev.SPI_write_async(port, [WRITE, 0x00, addr, value])
141        print(f"SPI_write_async in port {port}, status: {err}")
142
143        ## Set CS(pin0) to high
144        err = await dev.DO_writePins_async(DO_port, DO_index, [1])
145        print(f"DO_writePins_async in port {DO_port}, status: {err}")
146
147        '''
148        Read data via SPI
149        '''
150
151        ## Set CS(pin0) to low
152        err = await dev.DO_writePins_async(DO_port, DO_index, [0])
153        print(f"DO_writePins_async in port {DO_port}, status: {err}")
154
155        ## Read the written byte from the generated address
156        data = await dev.SPI_readAndWrite_async(port, [READ, 0x00, addr, DUMMY])
157        data = ['{:02x}'.format(value) for value in data]
158        print("read data :", data)
159
160        ## Set CS(pin0) to high
161        err = await dev.DO_writePins_async(DO_port, DO_index, [1])
162        print(f"DO_writePins_async in port {DO_port}, status: {err}")
163
164        '''
165        Close DO pins and SPI port
166        '''
167
168        ## Close SPI
169        err = await dev.SPI_close_async(port)
170        print(f"SPI_close_async in port {port}, status: {err}")
171
172        ## Close pin0 with digital output
173        err = await dev.DO_closePins_async(DO_port, DO_index)
174        print(f"DO_closePins_async in port {DO_port}, status: {err}")
175    except Exception as err:
176        pywpc.printGenericError(err)
177
178    finally:
179        ## Disconnect device
180        dev.disconnect()
181
182        ## Release device handle
183        dev.close()
184
185
186def main_for_spyder(*args):
187    if asyncio.get_event_loop().is_running():
188        return asyncio.create_task(main(*args)).result()
189    else:
190        return asyncio.run(main(*args))
191
192
193if __name__ == '__main__':
194    asyncio.run(main())  ## Use terminal
195    # await main()  ## Use Jupyter or IPython(>=7.0)
196    # main_for_spyder()  ## Use Spyder