micropython
micropython copied to clipboard
How can I use SPI for data transmission?
I have a question. How can I use SPI for data transmission. Can you give a simple example? I use the following, will prompt: TypeError: object with buffer protocol required
CS = pin16 DC = pin6
DC.write_digital(0) CS.write_digital(0) spi.write(0x0f) CS.write_digital(1)
The value passed into spi.write() needs to be a buffer type object., such as a bytearray Take a look at this article and it should explain it: https://forum.micropython.org/viewtopic.php?t=2797
Thank you very much, this is very comprehensive. I have just used spi.write(bytearray([0x0f])) and succeeded, but this transmission is very slow. I want to use the 1.8-inch LCD, and it takes 7S to complete the full screen.
There are several ways you can speed it up:
- use spi.init to increase the baudrate (see http://microbit-micropython.readthedocs.io/en/latest/spi.html#microbit.spi.init)
- avoid creatng and destroying small bytearray objects and instead keep one buffer and reuse it
- write more than a single byte at once, ideally fill the buffer with the data and write it all in one go
- don't update the whole screen, only the parts that actually changed
Unfortunately I have no experience with SPI. These articles may be of some help: https://learn.adafruit.com/micropython-hardware-spi-devices/spi-master https://forum.micropython.org/viewtopic.php?t=3323
The spi.init method has a baudrate parameter, but I am not sure if that is limited by the spi device or not.
@deshipu You beat me to it ;-). Well at least I used one of your postings as a resource.
Thank you, I tested a bit, this baud rate is also the largest 1M, and the same goes up, no calculation before, my entire screen brush even used 30S, scared me. I transferred all the data at one time. I used a logic analyzer to look at it. After sending a cycle of data, I paused for 7ms. I suspect that it may be a problem with the method call.
def LCD_WriteData_NLen16Bit(self, Data, DataLen):
LCD_DC.write_digital(1)
LCD_CS.write_digital(0)
for i in range(0, DataLen):
spi.write(bytearray([Data >> 8]))
spi.write(bytearray([Data & 0xff]))
LCD_CS.write_digital(1)
You are not sending it all in a single spi.write call. Try something like:
def lcd_write_data_16bit(self, data, count):
LCD_DC.write_digital(1)
LCD_CS.write_digital(0)
spi.write(data.to_bytes(2, 'little') * count)
LCD_CS.write_digital(1)
And I think that display works with up to 40000000 baud rate.
Thanks, this is a good idea. I'm sorry I don't know that this method is implemented
This LCD I can use 9M control on the STM32, but for the first time using micropython to develop micro:bit, this baud rate is a bit weird, but unfortunately http://microbit-micropython.readthedocs.io/en/latest/spi.html , not very detailed