What is SPI.read(nbytes, write=0xff) actually doing?

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
willemmerson
Posts: 2
Joined: Wed Oct 23, 2019 3:51 pm

What is SPI.read(nbytes, write=0xff) actually doing?

Post by willemmerson » Wed Oct 23, 2019 4:17 pm

I am successfully communicating with a CS5480 metering chip using micropython but I can't seem to do it using the normal IDF sdk on the ESP32. At some point I realised that it only works if I use SPI.read(nbytes, write=0xff), e.g. sending it 0xff when reading bytes but I don't know how this translates into IDF code. My micropython code is:

Code: Select all

        spi.write(bytearray([PAGE_FLAG | page]))
        spi.write(bytearray([address]))
        return spi.read(3, 0xff)
I have tried to do the same thing using IDF but it returns the wrong values:

Code: Select all

    spi_transaction_t page_transaction = {
            .tx_data={PAGE_FLAG | page},
            .length=1 * 8,
            .flags = SPI_TRANS_USE_TXDATA,
    };
    spi_transaction_t address_transaction = {
            .tx_data={address},
            .length=1 * 8,
            .flags = SPI_TRANS_USE_TXDATA,
    };
    spi_transaction_t read_transaction = {
            .tx_data={0xff, 0xff, 0xff},
            .length=3 * 8,
            .rx_buffer=rx_buffer,
            .rxlength=3 * 8,
            .flags = SPI_TRANS_USE_TXDATA,
    };

    pin_low(CS_METER34);
    ESP_ERROR_CHECK(spi_device_transmit(powermeter_device_handle, &page_transaction));
    ESP_ERROR_CHECK(spi_device_transmit(powermeter_device_handle, &address_transaction));
    ESP_ERROR_CHECK(spi_device_transmit(powermeter_device_handle, &read_transaction));
    pin_high(CS_METER34);

In fact I get nothing sensible back when writing 0xff. If I just try and read without sending the 0xff I at least get something back. Below I try and read 3 bytes from the same address 4 times, which should be 82 8F 5C:

Code: Select all

I (1372) CS5480: 82 02 00 
I (1472) CS5480: 5c 00 02 
I (1572) CS5480: 82 02 00 
I (1682) CS5480: 5c 00 02 
As you can see it's not quite working. I get a similar result if I take away the write=0xff from the micropython spi.read call above.
I have tried to look at the code for spi.read but can't even find the source file.

willemmerson
Posts: 2
Joined: Wed Oct 23, 2019 3:51 pm

Re: What is SPI.read(nbytes, write=0xff) actually doing?

Post by willemmerson » Wed Oct 23, 2019 5:17 pm

Turns out that I had it in half-duplex mode, when I changed it to full-duplex and sent 0xff it worked.

Post Reply