Search code examples
arduinoesp8266nodemcu

NodeMCU doesn't seem to set digital pin low


I'm writing a simple project, using NodeMCU as my board. I have 2 analog devices: moisture sensor and brightness sensor. Since NodeMCU has only one analog pin, I try to power them in turns. To do so, I connect them to digital pins of NodeMCU. Digital pins output 3.3V 20-40mA in HIGH state (checked that with multimeter). That must be enough to power those devices. In the LOW state, according to Arduino IDE docs, voltage must be 0V (and that also was checked) and the sensor must not receive any current and, thus, must not output anything to A0. However, at the end I get correlated results: if I flash light at the photoresistor, humidity data is also affected. And vice-versa. How can I avoid it? Here's the code, I'm using to do, what I described:

const int analogInputPin = A0; // Analog 0 (A0) on the board

// Several devices will use the same analog pin to send data
const int lightSensorResultPin = analogInputPin;
const int moistureSensorResultPin = analogInputPin;

const int lightSensorPowerPin = 16;
int lightSensorResult = 0;

const int moistureSensorPowerPin = 5;
int moistureSensorResult = 0;

void setup() {
  Serial.begin(9600);
  pinMode(lightSensorResultPin, INPUT);
  pinMode(lightSensorPowerPin, OUTPUT);
  digitalWrite(lightSensorPowerPin, LOW);

  pinMode(moistureSensorResultPin, INPUT);
  pinMode(moistureSensorPowerPin, OUTPUT);
  digitalWrite(moistureSensorPowerPin, LOW);
}

void loop() {
  /*==LIGHT SENSOR DATA READ BLOCK==*/
  digitalWrite(lightSensorPowerPin, HIGH);
  delay(1000);
  lightSensorResult = analogRead(lightSensorResultPin);
  digitalWrite(lightSensorPowerPin, LOW);
  delay(1000);
  /*==END OF LIGHT SENSOR DATA READ BLOCK==*/

  /*==MOISTURE SENSOR DATA READ BLOCK==*/
  digitalWrite(moistureSensorPowerPin, HIGH);
  delay(1000);
  moistureSensorResult = analogRead(moistureSensorResultPin);
  digitalWrite(moistureSensorPowerPin, LOW);
  delay(1000);
  /*==END OF MOISTURE SENSOR DATA READ BLOCK==*/

  Serial.print("Value on the light sensor: ");
  Serial.println(lightSensorResult); // Light value. Low for bright
  Serial.print("Value on the moisture sensor: ");
  Serial.println(moistureSensorResult); // Moisture value. Low for wet
}

UPD: Here's the schematic

Schematic


Solution

  • Instead of using digital outputs to switch on and off the different sensors, but combining their analog outputs, I would use an analog switch like 4066 to select which sensor you want to measure. enter image description here