// 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/elettronica-di-base/RaspberryPi/spi-c.htm // Compile: gcc multi.c -std=c99 -o multi // Run as user with R&W right on /dev/spidev0.* (NOT ROOT!) // vv@vvrpi ~ $ ./multi // Using MAX1240 - Read multiple voltage #include #include #include #include #include #include #include #include #include #define SPI_SPEED 2000000 // SPI frequency clock #define VREF 2.500 // MAX1240 voltag reference #define SAMPLES 1000 // Number of samples 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[SAMPLES]; uint16_t rx[SAMPLES]; // RX buffer (16 bit unsigned integer array) struct spi_ioc_transfer tr[SAMPLES]; for (int i = 0; i < SAMPLES; i++) { tr[i].tx_buf = (unsigned long)NULL; tr[i].rx_buf = (unsigned long)&rx[i]; tr[i].len = 2; tr[i].delay_usecs = 0; tr[i].speed_hz = SPI_SPEED; tr[i].bits_per_word = 8; tr[i].cs_change = 1; } // 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(SAMPLES), tr) < 1) exit_on_error ("Can't send SPI message"); for (int i = 0; i < SAMPLES; i++) // Convert to voltage { printf("RAW; %X ", rx[i]); if (!(rx[i] & 0x0080) ) printf (" FAIL "); // FAIL FAIL FAIL! (see text) data = ((rx[i] << 5) | (rx[i] >> 11)) & 0x0FFF; printf ("Data %d \n", data); volt[i] = 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 multiple data from MAX1240 on %s\n\n", device); for (int i = 0; i < SAMPLES; i++) printf("Voltage: %f V \n", volt[i]); close(fd); return (0); }