I want to setup mcp3008 on raspberry pi 4. I took this code
But it gives this error:
`I saw couple answers from the forums, which define the functions as globals I tried but probably I tried wrong also chatgpt said I did not downloaded the wiringSPI library but I did. I check all connections and mcp3008 works on python. I dont know how to fix this error.
Code:
#include <wiringPi.h>#include <stdio.h>#include <unistd.h>int readMCP3008(int &channel);#define CHANNELS 4#define SPI_CHANNEL 0#define REFERENCE_VOLTAGE 5.0int readMCP3008(int channel) { if (channel < 0 || channel >= CHANNELS) { fprintf(stderr, "Invalid channel.\n"); return -1; } unsigned char buffer[3]; buffer[0] = 0b11000000 | ((channel & 0x07) << 3); buffer[1] = 0; buffer[2] = 0; wiringPiSPIDataRW(SPI_CHANNEL, buffer, 3); int result = ((buffer[0] & 0x01) << 9) | (buffer[1] << 1) | ((buffer[2] & 0x80) >> 7); return result;}int main() { if (wiringPiSetup() == -1) { fprintf(stderr, "Error initializing WiringPi.\n"); return 1; } int spiHandle = wiringPiSPISetup(SPI_CHANNEL, 1000000); // Default SPI speed if (spiHandle == -1) { fprintf(stderr, "Error initializing SPI.\n"); return 1; } FILE *file = fopen("mcp3008_data.txt", "w"); if (file == NULL) { fprintf(stderr, "Error opening file for writing.\n"); return 1; } const int numSamples = 100; // Adjust as needed for (int sample = 0; sample < numSamples; sample++) { double value0 = (readMCP3008(0) * REFERENCE_VOLTAGE / 1023.0) - 1.5; double value1 = (readMCP3008(1) * REFERENCE_VOLTAGE / 1023.0) - 1.5; double value2 = (readMCP3008(2) * REFERENCE_VOLTAGE / 1023.0) - 1.5; double value3 = (readMCP3008(3) * REFERENCE_VOLTAGE / 1023.0) - 1.5; fprintf(file, "%.2f,%.2f,%.2f,%.2f", value0, value1, value2, value3); fprintf(file, "\n"); usleep(100000); // 100,000 microseconds = 100 milliseconds (adjust as needed) } fclose(file); return 0;}
`
Code:
g++ -Wall -o "mcp3008_read" "mcp3008_read.cpp" (/home/*/Desktop dizininde)mcp3008_read.cpp: In function ‘int readMCP3008(int)’:mcp3008_read.cpp:27:5: error: ‘wiringPiSPIDataRW’ was not declared in this scope 27 | wiringPiSPIDataRW(SPI_CHANNEL, buffer, 3); | ^~~~~~~~~~~~~~~~~mcp3008_read.cpp: In function ‘int main()’:mcp3008_read.cpp:41:21: error: ‘wiringPiSPISetup’ was not declared in this scope; did you mean ‘wiringPiSetup’? 41 | int spiHandle = wiringPiSPISetup(SPI_CHANNEL, 1000000); // Default SPI speed | ^~~~~~~~~~~~~~~~ | wiringPiSetup`
Statistics: Posted by emiracno — Sun Mar 03, 2024 1:35 pm — Replies 0 — Views 16