No, you’re misunderstanding the timeline here.
SPI is a clocked bus. No data can be sent or received unless there’s a clock. When there is a clock, bits are sent and received at the same time; in effect, this means that both ends will have whatever they are going to send ready to go before the clock starts.
This means, when you write PN532_SPI_STATREAD, you will receive a byte. This byte WILL NOT be the status value - because until the last bit of the command byte has been clocked over the bus, the chip does not even know you want to read the status. Reading the status takes 16 clocks - or two bytes written by the master. You need to write the status read command, discard the junk byte that was received during the command transmission, then write a junk byte (which will be ignored by the slave) during which the status byte will be received by the master.
To illustrate how the API works (and there are clearer, multibyte versions in release-14 you’ll be glad to know), here’s what happens during each call:
hardware.spi257.write(PN532_SPI_STATREAD); // 8 clocks are generated and the byte is sent on the bus. The received byte is stored in a holding register, but is not returned.
value = hardware.spi257.read(1); // no clocks are generated. The contents of the holding register, populated by the last spi write call, are returned.
Re-writing your functions to be more what you need:
`function readspistatus() {
hardware.pin1.write(0);//pull CS low
imp.sleep(0.002);
// Send status command to PN532; ignore returned byte
spi_txrx(PN532_SPI_STATREAD);
// Collect status response, send junk 0x00 byte
local value = spi_txrx(0x00);
hardware.pin1.write(1);//pull CS high
return value;
}
function spi_txrx(byte) {
// Write the single byte
hardware.spi257.write(format("%c", byte));
// Collect the response from the holding register
local resp=hardware.spi257.read(1);
// Show what we sent
server.log(format("SPI tx %02x, rx %02x", byte, resp[0]));
// Return the byte
return resp[0];
}`
Give that a try?