Skip to content

Instantly share code, notes, and snippets.

@theapi
Created May 27, 2018 10:07
Show Gist options
  • Save theapi/8490086bd158cbaf8f928c80c175c6c3 to your computer and use it in GitHub Desktop.
Save theapi/8490086bd158cbaf8f928c80c175c6c3 to your computer and use it in GitHub Desktop.
// spi.c
//
// Example program for bcm2835 library
// Shows how to interface with SPI to transfer a byte to and from an SPI device
//
// After installing bcm2835, you can build this
// with something like:
// gcc -o spi spi.c -l bcm2835
// sudo ./spi
//
// Or you can test it before installing with:
// gcc -o spi -I ../../src ../../src/bcm2835.c spi.c
// sudo ./spi
//
#include <bcm2835.h>
#include <stdio.h>
int main(int argc, char **argv)
{
if (!bcm2835_init())
{
printf("bcm2835_init failed. Are you running as root??\n");
return 1;
}
if (!bcm2835_spi_begin())
{
printf("bcm2835_spi_begin failed. Are you running as root??\n");
return 1;
}
bcm2835_spi_setBitOrder(BCM2835_SPI_BIT_ORDER_MSBFIRST); // The default
bcm2835_spi_setDataMode(BCM2835_SPI_MODE0); // The default
bcm2835_spi_setClockDivider(BCM2835_SPI_CLOCK_DIVIDER_65536); // The default
bcm2835_spi_chipSelect(BCM2835_SPI_CS0); // The default
bcm2835_spi_setChipSelectPolarity(BCM2835_SPI_CS0, LOW); // the default
uint8_t send_data = 3;
while(1) {
// Send a byte to the slave and simultaneously read a byte back from the slave
// If you tie MISO to MOSI, you should read back what was sent
bcm2835_delay(1000);
send_data++;
uint8_t read_data = bcm2835_spi_transfer(send_data);
printf("Sent to SPI: %u. Read back from SPI: %u.\n", send_data, read_data);
}
bcm2835_spi_end();
bcm2835_close();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment