The LSB in data received by master is being dropped when using SPI communication between 2 atmega328ps

37 views Asked by At

I've connected two atmega328ps using SPI, one as master and the other as slave. When trying to send data from slave to master the least significant bit in the original data is being dropped, it's like only 7 bits of data are being shifted instead of 8.eg when the slave sends 0b01110111, the master receives 0b00111011, the LSB is missing, this makes no sense to me as the slave on the other hand receives the entire 8 bits of data during the same transmission cycle.

code for master:

int main(void)
{
    DDRC |=  (1 << DATAPIN)|(1 << CLOCKPIN)|(1 << LATCHPIN) |(1 << RW)|(1 << RS)|(1 << EN);
    LCD_Init();
    SPI_MasterInit();
    char slave_data;
    while (1)
    {       slave_data = spi_master_receive();
            LCD_Char(slave_data);
            _delay_ms(5000);
            PORT_SPI |= (1<<SS);
            _delay_ms(5000);
            LCD_Clear();
        }
    }
char spi_master_receive(void)
{   PORT_SPI &= ~(1<<SS);
    /*time for slave to set up data register*/
    _delay_us(20);
    /*write to data to in order to shift data from slave to master*/
    SPDR = 'w';
    /* wait for interrupt flag*/
    while (!(SPSR & (1<<SPIF)));
    /*read data*/
    char slave_data = SPDR & 0xFF; 
    return slave_data;
}

code for slave:

int main(void)
{
    DDRC |=  (1 << DATAPIN)|(1 << CLOCKPIN)|(1 << LATCHPIN) |(1 << RW)|(1 << RS)|(1 << EN);
    LCD_Init();
    SPI_slave_init();
    while (1)
    {   char test = 'v';
        while(PORT_SPI & (1<<SS));
        char slave_data = spi_slave_transmit(test);
        LCD_Char(slave_data);
        _delay_ms(5000);
        LCD_Clear();    
    }   
}
char spi_slave_transmit(char character)
{   /*write to SPDR to send a char to master*/
    SPDR = character;
    /*wait for master to complete transmission*/
    while (!(SPSR & (1<<SPIF)));
    _delay_us(10);
    char master_data = SPDR;
    return master_data;
}

I have checked with the atmega328p datasheet and I do not see anything that could be the cause of this issue. I have also tried adjusting the data order (DORD) bit hoping that maybe the order of shifting data was the problem but that is not either lastly I have experimented with clock settings and also tried adding delays thinking that maybe the data needed more time to complete shifting but that didn't help. Any insights or suggestions would be greatly appreciated.

0

There are 0 answers