Main Site Documentation

SPI bit corruption


I’m trying to interface my FEZ Panda with an ATtiny2313 via SPI. The ATtiny is acting as an encoder counter that reports counts via SPI.

I’ve clocked it as slow as it will go (200 kHz apparently), but there is still bit-level corruption. Here the ATtiny is responding to a command with a single byte count, where the count should be staying constant:


191 = 10111111
223 = 11011111

This is the Panda code I’m using

namespace PandaTest
    public class Program
        public static void Main()
            // Blink board LED

            bool ledState = false;

            OutputPort led = new OutputPort((Cpu.Pin)FEZ_Pin.Digital.LED, ledState);

            SPI.Configuration spiConfig = new SPI.Configuration(
                (Cpu.Pin)FEZ_Pin.Digital.Di9, false, 0, 0,
                false, true, 200, SPI.SPI_module.SPI1,
                (Cpu.Pin)FEZ_Pin.Digital.Di10, true);
            SPI spi = new SPI(spiConfig);
            byte[] spi_tx = new byte[1],
                spi_rx = new byte[1];

            while (true)
                // Sleep for 500 milliseconds

                byte channel = 0;

                spi_tx[0] = (byte)((1 << 2) | channel);
                spi.WriteRead(spi_tx, spi_rx);


                // toggle LED state
                ledState = !ledState;


Both Panda and ATtiny are set to CPOL=0, CPHA=0 (clock idle state 0, reads data on the rising edge). ATtiny is configured as a slave, and it is definitely asserting the BUSY signal in time (the byte is getting sent, just corrupted somehow).

Adding the Thread.Sleep(1); didn’t change results

Any ideas what’s going on here?


Can we clean up the test loop and try again?

Make a loop that send fixed number to your Atmega then the atmega always sends back a fix number

Note that spi.Write is also reading but you are basically dumping the read data. I suggest you do nto use spi.Write will you fully understand the mechanism.

SPI bus always swaps a byte between TX and RX side. It is not possible to send only or receive only.

Look at image on the right