Node MCU 32s irregular input in digital read

Neel91
Posts: 2
Joined: Sat Aug 06, 2022 7:19 am

Node MCU 32s irregular input in digital read

Postby Neel91 » Sat Aug 06, 2022 8:04 am

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);
}
input.png
this is the serial plot of the input i am getting
input.png (39.68 KiB) Viewed 2166 times

ESP_Sprite
Posts: 9739
Joined: Thu Nov 26, 2015 4:08 am

Re: Node MCU 32s irregular input in digital read

Postby ESP_Sprite » Sun Aug 07, 2022 1:42 am

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.

Neel91
Posts: 2
Joined: Sat Aug 06, 2022 7:19 am

Re: Node MCU 32s irregular input in digital read

Postby Neel91 » Sun Aug 07, 2022 10:35 am

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?

ESP_Sprite
Posts: 9739
Joined: Thu Nov 26, 2015 4:08 am

Re: Node MCU 32s irregular input in digital read

Postby ESP_Sprite » Sun Aug 07, 2022 10:50 am

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.

Who is online

Users browsing this forum: Bing [Bot] and 89 guests