MicroPython ESP8266 SPI接口发送错误数据

MicroPython ESP8266 SPI interface sends wrong data

一个非常基本的电路使用 MicroPython 和 SPI 接口将 ESP8266 MCU 连接到 74HC595 移位寄存器。这就是我尝试发送数据的方式:

from machine import Pin, SPI
hspi = SPI(-1, baudrate=50000, polarity=0, phase=0, sck=Pin(14), mosi=Pin(13), miso=Pin(12), bits=8)
latch_pin = Pin(15, Pin.OUT)
latch_pin.off()

def send(s):
    hspi.write(s)
    latch_pin.on()
    latch_pin.off()

为了测试,我在输出引脚和 +5V(通过 100 欧姆电阻)之间放置了 8 个 LED 以查看发生了什么,并尝试使用此测试功能发送数据:

import time
def test_one(s):
    send(chr(int(s)))
    time.sleep(0.5) # only to be able to examine the leds after data was sent

def test():
    [test_one(s) for s in [
        '0b00000000',
        '0b10000000',
        '0b01000000',
        '0b00100000',
        '0b00010000',
        '0b00001000',
        '0b00000100',
        '0b00000010',
        '0b00000001',
        '0b01111111',
        '0b10111111',
        '0b11011111',
        '0b11101111',
        '0b11110111',
        '0b11111011',
        '0b11111101',
        '0b11111110',
        '0b11111111']]

test()

正如你所见,这个测试中有移动的1和移动的零。结果很有趣。值 0000 0000 被传输为 1100 0010。之后,所有设置了一位的值都被正确传输。那么 0111 1111 又是正确的。在那之后,所有的值又是错误的。我用逻辑分析仪检查了输出,这些值似乎是以两个字节而不是一个字节发送的。

第一个好的值是 1000 0000:

最后一个单1位的值0000 0001也传好了:

最后一个有效值是 0111 1111:

下一个应该是 1011 1111 但不是那个,而是 1100 0010 1011 1111 被转移了。例如。发送的不是一个字节,而是两个字节:

我的第一个想法是,也许 SPI 使用的是 7 位而不是 8 位。但那是不可能的,因为那样的话 1000 0000 也应该是错误的。 (此外,SPI 对象是使用 bits=8 参数创建的。)顺便说一句,我也尝试过硬件 SPI (id=1),但它有同样的问题。所以这一定是我程序的问题,而不是硬件问题,但我卡住了,无法解决这个问题。

send() 函数使用 chr() 创建单个字符。任何人都可以解释为什么一些单个字符作为两个字节发送,而其他字符作为一个字节发送吗?

MicroPython 是 based on Python 3...

MicroPython aims to implement the Python 3.4 standard (with selected features from later versions) with respect to language syntax, and most of the features of MicroPython are identical to those described by the “Language Reference” documentation at docs.python.org.

...所以 chr returns 一个 Unicode 字符串。要指定要通过 SPI 发送的确切字节,您需要为 SPI write 方法提供一个 bytes 对象。

如果您将代码中的 send(chr(int(s))) 替换为 send(bytes([int(s)])),它应该会发送您期望的位模式。