0

I have a very simple code for a controller I'm working on for a robot.

void setup() {
  // put your setup code here, to run once:
  pinMode(3,INPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println(digitalRead(3));
}

The only problem is that I can't get a constant reading on switches because when I flick the switch I will get a constant stream of 1s, but when I flick the switch off I get a sporadic stream of ones and zeros. I have noticed though that if I put my finger on the USB port leading from my Arduino Nano I get a constant stream of 1s when on and zeros when off.

Does anyone have a recommendation to get around this problem or simulate touch on the USB port?

2
  • Is the GND correctly connected? Sounds like that's your problem – Tarick Welling May 19 '19 at 20:15
  • It sounds more like you have no pullup or pulldown resistor wired. When using pinMode(pin, INPUT_PULLUP), you are activating the Arduinos internal pullup resistor. – chrisl May 19 '19 at 21:10
2

Sounds like you need a pull-down resistor.

If a CMOS input like and Arudino digital input isn't attached to anything it will "float", bouncing between 1 and 0.

Attach a 10k resistor between the input pin and ground (before the switch). That way, if the switch is off/open, the resistor pulls the input to ground.

If the switch is on/closed, it feeds +5V into the pin, overwhelming the resistor.

(Note that you can instead use a pull-up resistor, and then have the switch connect to ground instead of +5 volts. When you do this the input is reversed {HIGH if the switch is not pressed and LOW if the switch is pressed.} There is an internal pull-up resistor on the digital input pins that you can connect by using the setting INPUT_PULLUP instead of INPUT when you configure the pin with the pinMode() function. That way you don't need an extra resistor.)

Also note that in addition to needed a pull-up or pull-down resistor, you may need to debounce your switch. You can do this by writing your code that detects switch presses to ignore changes for 100 ms or so. This avoids the rapid on/off/on/off jitter you often get from switches as their contacts transition from open to closed (or closed to open.)

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.