// Rapsberry Pi: SPI con wiring Pi - Versione 1.1 - Marzo 2017 // Copyright (c) 2013-2017, 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 #define SPI_SPEED 2000000 // SPI frequency clock (2 MHz) #define SPI_CH 0 // SPI channel: 0 or 1 #define VREF 2.500 // MAX146 voltage reference #define MAX146_CONTROL_BYTE 0x8F // 1000 1111 = Unipolar, single ended, external clock (see datasheet) #define MAX146_CH 7 // ADC channel to read: 0...7 #define MAX146_BUFFER_SIZE 3 // Read and write buffer size #define SAMPLES 100 // Value to read #define MILLI 825 // Delay time for Tc = 1000 s #include #include #include #include #include #include #include #include #include #include int main(int argc, char *argv[]) { int fd; // Output file for post-analisys double volt[SAMPLES]; // Samples uint16_t data; uint8_t rtx[MAX146_BUFFER_SIZE]; // RX/TX buffer (3 byte) int start_time; // For timing wiringPiSPISetup(SPI_CH, SPI_SPEED); // Set channel and speed start_time = micros(); // Starting time for (int i = 0; i < SAMPLES; i++) { // Read SAMPLES samples switch (MAX146_CH) // See data sheet { case 0: rtx[0] = MAX146_CONTROL_BYTE | 0x00; break; case 1: rtx[0] = MAX146_CONTROL_BYTE | 0x40; break; case 2: rtx[0] = MAX146_CONTROL_BYTE | 0x10; break; case 3: rtx[0] = MAX146_CONTROL_BYTE | 0x50; break; case 4: rtx[0] = MAX146_CONTROL_BYTE | 0x20; break; case 5: rtx[0] = MAX146_CONTROL_BYTE | 0x60; break; case 6: rtx[0] = MAX146_CONTROL_BYTE | 0x30; break; case 7: rtx[0] = MAX146_CONTROL_BYTE | 0x70; break; default: printf("Unknow error\n\n"); exit(-1); } rtx[1] = 0; rtx[2] = 0; wiringPiSPIDataRW(SPI_CH, rtx, MAX146_BUFFER_SIZE); // Read fron SPI // Adjust bit order from buffer (see datasheet) data = rtx[1]; data = data << 5; data = data | (rtx[2] >> 3); // Convert to voltage volt[i] = VREF * data / 4096; delayMicroseconds (MILLI); // Stop time //printf("Voltage applied to CH%i = %f V\n", MAX146_CH, volt[i]); // Very long time... } printf("Elapsed time: %i us\n\n", micros() - start_time); FILE *fp; // Save on text file samples fp = fopen("voltage.txt", "w"); for (int i = 0; i < SAMPLES; i++) fprintf(fp, "%i %f\n", i, volt[i]); fclose(fp); return (0); }