从 mcp3008 ADC 读取时出现错误。下面的函数在接收到 3.3V 输入时返回 127。由于它是一个 10 位 ADC,它应该返回 1023。
我已经正确定义了我的引脚号,并且包括了 stdio.h 和wiringPi.h。任何帮助表示赞赏。
int main(void) {
int adcValue = 0;
wiringPiSetup();
pinMode(csPin, OUTPUT);
pinMode(sclkPin, OUTPUT);
pinMode(mosiPin, OUTPUT);
pinMode(misoPin, INPUT);
while(1) {
delay(10);
adcValue = readADC(CHAN0);
if (adcValue == -1)
printf("Error reading from %i \n", CHAN0);
else
printf("Chan0: %i \n", adcValue);
}
}
int readADC(int adcChan) {
// Variables
unsigned char dataOut = 0;
unsigned char adcout = 0;
int i, j = 0;
if ((adcChan > 7) || (adcChan < 0)) {
return -1;
}
digitalWrite(csPin, HIGH);
digitalWrite(sclkPin, LOW);
digitalWrite(csPin, LOW);
dataOut = adcChan;
dataOut |= 0x18;
dataOut <<= 3;
for (i = 0; i < 5; i++) {
if (dataOut & 0x80) {
digitalWrite(mosiPin, HIGH);
} else {
digitalWrite(mosiPin, LOW);
}
dataOut <<= 1;
digitalWrite(sclkPin, HIGH);
digitalWrite(sclkPin, LOW);
}
adcout = 0;
for (j = 0; j < 12; j++) {
digitalWrite(sclkPin, HIGH);
digitalWrite(sclkPin, LOW);
adcout <<= 1;
if (digitalRead(misoPin)) {
adcout |= 0x1;
}
}
digitalWrite(csPin, HIGH);
adcout >>= 1;
return adcout;
}