// Rapsberry Pi: SPI con wiring Pi - Versione 1.2 - Marzo 2018 // Copyright (c) 2013-2018, Vincenzo Villa // Creative Commons | Attribuzione - Condividi allo stesso modo 4.0 Internazionale (CC BY-SA 4.0) // Creative Commons | Attribution-Share Alike 4.0 Unported // https://www.vincenzov.net/tutorial/RaspberryPi/spi-wpi.htm // MCP3202 (SPI ADC) // wirinPi 2.44 // Linux raspberrypi 9.4 #include #include #include #include #include "wiringPi.h" #include "wiringPiSPI.h" #include #define SPI_CLOCK 1000000 // 1 MHz #define MCP3202_CH 1 // /dev/spidev0.1 #define VREF 3.3 // Voltage referenze (= VDD) #define COUNT 4096 // 2 ^ 12 // See MCP3202 data sheet FIGURE 6-1 SPI Communication using 8-bit segments #define MCP3202_START 1 // 0000 0001 #define MCP3202_CONFIG 0xA0 // 101x xxxx (Single-Ended + Channel 0 + MSB first) #define MCP2002_BUFFER_SIZE 3 int main(int argc, char** argv) { uint8_t buffer[MCP2002_BUFFER_SIZE]; // See FIGURE 6-1 on data sheet int error; // From wirinPi library double voltage; // Voltage from ADC int ADC; // Voltage from ADC, as integer 0 -> 4095 setbuf(stdout, NULL); // NetBeans hack: disable buffering on stdout error = wiringPiSPISetup(MCP3202_CH, SPI_CLOCK); // Set SPI clock // if (error ....) buffer[0] = MCP3202_START; // Set output buffrt with MCP3202 configuration buffer[1] = MCP3202_CONFIG; buffer[2] = 0; wiringPiSPIDataRW(MCP3202_CH, buffer, MCP2002_BUFFER_SIZE); // Read and write buffer ADC = (buffer[2] | ((buffer[1] & 0x0F) << 8)); voltage = 3.3 / COUNT * ADC; // Convert to 12 bit result printf("Data read: 0x%02hhx 0x%02hhx 0x%02hhx -> %d -> %4.3f V\n", buffer[0], buffer[1], buffer[2], ADC, voltage); return (EXIT_SUCCESS); }