我想在树莓派 4 上设置 mcp3008。我拿了这个代码
#include <wiringPi.h>
#include <stdio.h>
#include <unistd.h>
int readMCP3008(int &channel);
#define CHANNELS 4
#define SPI_CHANNEL 0
#define REFERENCE_VOLTAGE 5.0
int 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;
}
但它给出了这个错误:
`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
`
我从论坛上看到了几个答案,它们将函数定义为我尝试过的全局函数,但可能我尝试错了,chatgpt 说我没有下载 WiringSPI 库,但我下载了。我检查了所有连接,mcp3008 在 python 上运行。我不知道如何修复这个错误。
检查标头:https://github.com/WiringPi/WiringPi/blob/master/wiringPi/wiringPiSPI.h
头文件
wiringPi.h
没有包含wiringPiSPI.h
,需要你自己做。