Trouble when connecting limit switch

Hi! I am trying to connect a limit switch but the output in my serial monitor does not make sense.

Wiring goes from Arduino UNO digital port 2 to limit switch, then from limit switch to 10k ohm resistor, then to Arduino ground.

When the limit switch is connected and I press it i get 0 repeatedly in the serial monitor, but when I release the button the serial monitor alternates between 0 and 1 at seemingly random intervals. Even when i disconnect the switch it still reads lots of 0s and 1s randomly. I would expect it to read either 0 or 1, not both. Is there something wrong with my arduino? Or am i doing something wrong? I have tried different cables, different switches (same brand/type) and different connector/pins.

Here is the code im using :

Kodeutsnittint BUTTON_PIN = 2;

int buttonState =0;

void setup() {

pinMode (BUTTON_PIN, INPUT);

Serial.begin(9600);

}

void loop() {

buttonState = digitalRead(BUTTON_PIN);

Serial.println(buttonState);

}Kodeutsnitt

Floating Inputs and its Mitigating Measure in Arduino

Floating Inputs and its Mitigating Measure in Arduino.

Help us help you.

Please follow the advice given in the link below when posting code, in particular the section entitled 'Posting code and common code problems'

Use code tags (the </> icon above the compose window) to make it easier to read and copy for examination

Use the IDE autoformat tool (ctrl-t or Tools, Auto format) before posting code in code tags.

Please include the entire error message. It is easy to do. There is a button (lower right of the IDE window) called "copy error message". Copy the error and paste into a post in code tags. Paraphrasing the error message leaves out important information.

Please post a schematic.

Please post an image of your project.

Please describe the problem better then you just did.

Use


pinMode (BUTTON_PIN, INPUT_PULLUP);

Sorry, will do better on my next post

This fixed it, thanks!!

Your topic has been moved to a more suitable location on the forum. Introductory Tutorials is for tutorials that e.g. you write, not for questions. Feel free to write a tutorial once you have solved your problem :wink:

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.