-1

I'm using an ESP8266 (NodeMCU Dev Kit v1) to read analog data via an MCP3008 ADC chip.

However I'm receiving only zeros when I know non-zero data should be present. I'm using the following code, which works perfectly when using the MCP3008 with my Arduino UNO. Using verbose mode on compilation, I can confirm that when compiling for the ESP8266, that is indeed linking the ESP8266 SPI library.

Am I missing something here in the code?

#include <SPI.h>

#define CS_PIN 15 // Use 10 when compiling for Arduino

int adcRead(int channel) {
  if ((channel > 7) || (channel < 0)) {
    return -1;
  }

  digitalWrite(CS_PIN, LOW);

  SPI.transfer(1);
  uint8_t r1 = SPI.transfer((channel + 8) << 4);
  uint8_t r2 = SPI.transfer(0);

  digitalWrite(CS_PIN, HIGH);

  return ((r1 & 3) << 8) + r2;
}

void setup() {
  SPI.begin();
  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE0);
  SPI.setFrequency(1000000); // 1 MHz -- remove line when running on Arduino UNO
  Serial.begin(9600);
  digitalWrite(CS_PIN, HIGH);
}

void loop() {
  Serial.println(adcRead(0));
  delay(50);
}

In terms of wiring, I have the following

MCP3008   ESP8266
V_DD      3v3
V_REF     3v3
AGND      GND
CLK       GPIO14 (D5)
D_OUT     GPIO12 (D6)
D_IN      GPIO13 (D7)
CS        GPIO15 (D8)
DGND      GND
  • I dont see any pinMode(CS_PIN, OUTPUT); – TisteAndii Apr 23 '16 at 22:29
  • That fixed it! Guess I managed to overlook that. – user1569339 Apr 23 '16 at 22:33
1

I was having trouble with this code and setup with the Adafruit Feather HUZZAH ESP8266.

Solution

In addition to adding the pinMode(CS_PIN, OUTPUT); to setup(), I also dropped the frequency to something much lower. In my case, dropping the frequency to 10000 gave me good readings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.