AdSense

Sunday 23 June 2013

SPI communication between ATMega and Raspberry PI

(Deutsche Version) I measure the temperature in my room (see ATMega - ATMega - Temperature measurement with the DS18S2). The temperature is read by an ATMega. This data is sent via SPI (see ATMega - Hardware SPI) to the Raspberry PI which collects the data and creates a plot. The missing part in the chain is the communication between ATMega and Raspberry PI. After some time of research, I found a good implementation of SPI on the Raspberry PI (http://www.airspayce.com/mikem/bcm2835/) called bcm2835. The code on the Raspberry PI is the following:

#include <bcm2835.h>
int main (int atgc, char** argv)
{
  if (!bcm2835_init())
  {
    return 1;
  }
  bcm2835_spi_begin();
  bcm2835_spi_setBitOrder(BCM2835_SPI_BIT_ORDER_MSBFIRST);
  bcm2835_spi_setDataMode(BCM2835_SPI_MODE0);
  //CLOCK_DIVIDER: more information is provided here
  bcm2835_spi_setClockDivider(BCM2835_SPI_CLOCK_DIVIDER_65536);
  bcm2835_spi_chipSelect(BCM2835_SPI_CS0);
  bcm2835_spi_setChipSelectPolarity(BCM2835_SPI_CS0, LOW);

  //An example which sends a byte and then receives a byte
  char sendBits = 0b11111111;
  char returnBits = 0;

  while(true)
  {
    bcm2835_spi_transfer(sendBits);

    //send dummy bytes for receiving
    returnBits = bcm2835_spi_transfer(0);

  }
}


The code on the ATMega is the following (the three SPI functions explained in ATmega - Hardware-SPI have to be present in the program):

#include <avr/io.h>
int main()
{
  SPI_SlaveInit();
  char returnBits = 0;
  char sendBits = 0b11111111;
  while(true)
  {
    data = SPI_SlaveReceive();
    SPI_SlaveSend(sendBits);
  }
}

2 comments:

  1. I guess you've connected CS0 (RPI) to the SS' pin of the atmega here?

    ReplyDelete
    Replies
    1. Yeah, that's right. I connected SCLK-SCK, MISO-MISO, MOSI-MOSI and CE0-SS. You can read the pin assignment for the Raspberry PI here: http://elinux.org/RPi_Low-level_peripherals#General_Purpose_Input.2FOutput_.28GPIO.29 and for the ATmega8 here: http://www.atmel.com/Images/Atmel-2486-8-bit-AVR-microcontroller-ATmega8_L_summary.pdf

      Delete