Page 1 of 1
Node MCU 32s irregular input in digital read
Posted: Sat Aug 06, 2022 8:04 am
by Neel91
I am using the following code to read digital input. I am using an Node MCU-ESP32s and arduino IDE. The input is irregular, always fluctuating between 1&0
void setup() {
Serial.begin(9600);
pinMode(32,INPUT); // put your setup code here, to run once:
pinMode(2,OUTPUT);
}
void loop() {
int i=digitalRead(32);
__asm__("MEMW");
digitalWrite(2,i);
Serial.println(i);
delay(25);
}
- this is the serial plot of the input i am getting
- input.png (39.68 KiB) Viewed 2165 times
Re: Node MCU 32s irregular input in digital read
Posted: Sun Aug 07, 2022 1:42 am
by ESP_Sprite
Do you have anything connected to that GPIO? If not, this behaviour is correct: the level on an unconnected input is undefined, as it's not pulled to a defined level and as such picks up stray electromagnetic waves from the environment.
Re: Node MCU 32s irregular input in digital read
Posted: Sun Aug 07, 2022 10:35 am
by Neel91
Thanks for the reply
This screenshot is for an open GPIO pin . When i connect the GPIO to the proximity sensor it stays on while the sensor is on but when the sensor is off it reverts back to the irregular behaviour. Can this be avoided somehow?
Re: Node MCU 32s irregular input in digital read
Posted: Sun Aug 07, 2022 10:50 am
by ESP_Sprite
You should look at the specs of the sensor: if it's 'open-drain' or 'open-collector', it can only pull the line down and when it's active the level still is not defined.
Defining the level is done using a pullup or pulldown resistor. You can add a resistor of, say, 10K from the IO to ground or 3v3, but you can also do that by enabling the internal pullup: pinMode(32, INPUT_PULLUP); (Or INPUT_PULLDOWN, dependent on what your sensor needs, but that one doesn't usually happen.) Note that for the ESP32, pins 34 and higher don't have the pullup/pulldown capability and you need to add an external resistor for those.