// Rapsberry Pi: SPI in C - Versione 0.51 - Luglio 2013 // Copyright (c) 2013, Vincenzo Villa (https://www.vincenzov.net) // Creative Commons | Attribuzione-Condividi allo stesso modo 3.0 Unported. // Creative Commons | Attribution-Share Alike 3.0 Unported // https://www.vincenzov.net/tutorial/RaspberryPi/spi-c.htm // Compile: gcc adc.c -std=c99 -o adc // Run as user with R&W right on /dev/spidev0.* (NOT ROOT!) // vv@vvrpi ~ $ ./adc // Using MAX1240 - Read single voltage #include #include #include #include #include #include #include #include #include #define SPI_SPEED 2100000 // SPI frequency clock #define VREF 2.500 // MAX1240 voltag reference static const char *device = "/dev/spidev0.0"; // MAX1240 CD to RPi CS0 static uint8_t mode = SPI_MODE_0; // SPI_MODE_0 static void exit_on_error (const char *s) // Exit and print error code { perror(s); abort(); } int main(int argc, char *argv[]) { int fd; int data; double volt; uint16_t rx; // RX buffer (16 bit unsigned integer) struct spi_ioc_transfer tr = { .tx_buf = (unsigned long)NULL, .rx_buf = (unsigned long)&rx, .len = 2, .delay_usecs = 0, .speed_hz = SPI_SPEED, .bits_per_word = 8, .cs_change = 0, }; // Open SPI device if ((fd = open(device, O_RDWR)) < 0) exit_on_error ("Can't open SPI device"); // Set SPI mode if (ioctl(fd, SPI_IOC_WR_MODE, &mode) == -1) exit_on_error ("Can't set SPI mode"); // Read data if (ioctl(fd, SPI_IOC_MESSAGE(1), &tr) < 1) exit_on_error ("Can't send SPI message"); // Adjust bit order from buffer (see text and data sheet) data = ((rx << 5) | (rx >> 11)) & 0xFFF; // Convert to voltage volt = VREF * data / 4096; printf("Rapsberry Pi: SPI in C - Versione 0.5 - Luglio 2013\n"); printf("Copyright (c) 2013, Vincenzo Villa (https://www.vincenzov.net)\n"); printf("Creative Commons | Attribuzione-Condividi allo stesso modo 3.0 Unported.\n"); printf("Creative Commons | Attribution-Share Alike 3.0 Unported\n"); printf("https://www.vincenzov.net/tutorial/elettronica-di-base/RaspberryPi/spi-c.htm\n\n"); printf("Reading data from MAX1240 on %s\n\n", device); printf("Voltage: %f V - Hex value: 0x%X - Raw value: 0x%X)\n\n", volt, data, rx ); // Check for timing (see data shet and text) if (!(rx & 0x0080) ) printf ("FAIL: EOC in not 1 \n\n"); close(fd); return (0); }