Page 15 of 21
Chapter 18
Page 312
#include <bcm2835.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
if (!bcm2835_init())
{
return 1;
}
if (!bcm2835_spi_begin())
{
return 1;
}
bcm2835_spi_setDataMode(BCM2835_SPI_MODE0);
bcm2835_spi_setClockDivider(BCM2835_SPI_CLOCK_DIVIDER_8192);
bcm2835_spi_chipSelect(BCM2835_SPI_CS0);
bcm2835_spi_setChipSelectPolarity(BCM2835_SPI_CS0, LOW);
bcm2835_spi_setBitOrder(BCM2835_SPI_BIT_ORDER_MSBFIRST);
char buf[] = {0x01, 0x80, 0x00};
char readBuf[3];
bcm2835_spi_transfernb(buf, readBuf, 3);
int data = ((int)readBuf[1] & 0x03) << 8 | (int)readBuf[2];
float volts = (float)data * 3.3f / 1023.0f;
printf("%f", volts);
bcm2835_spi_end();
bcm2835_close();
return (EXIT_SUCCESS);
}