1

I am learning Arduino and pardon me if this is nooby. I am trying to make an LED glow when the tilt switch is tilted. The LED should not glow if the tilt is in normal position. The circuit and the code are in the attached image.

Based on my understanding of the code, I thought that when the tilt switch pin 5 is passed with HIGH signal from 5V the IF condition gets satisfied and tje LED on pin 13 would glow.

But it does not happen. The LED just glows before I tilt the tilt switch. Could you please clarify/correct my mistake. Thank you.

Circuit

Attaching the code below as per suggestion

int ledPin = 13;
int switchPin = 5;

void setup() {
  pinMode(ledPin,OUTPUT);
  pinMode(switchPin,INPUT);  
}

void loop() {
  Serial.begin(9600);
  if (digitalRead(switchPin) == HIGH) {
    digitalWrite(ledPin,HIGH);
    Serial.print("we are here");
  }
  if (digitalRead(switchPin) == LOW) {
    digitalWrite(ledPin,LOW);
    Serial.print("there");
  }
}
  • 1
    Don't paste an image of the code. Code is text -- just paste the text right into the question, select it and type CTRL-K to format it as code. – jose can u c Mar 30 '18 at 21:13
  • int ledPin = 13; int switchPin = 5; void setup() { pinMode(ledPin,OUTPUT); pinMode(switchPin,INPUT); } void loop() { Serial.begin(9600); if (digitalRead(switchPin) == HIGH) { digitalWrite(ledPin,HIGH); Serial.print("we are here"); } if (digitalRead(switchPin) == LOW) { digitalWrite(ledPin,LOW); Serial.print("there"); } } – user2823393 Mar 30 '18 at 21:15
  • 1
    Edit your question -- don't put the code as a comment. – jose can u c Mar 30 '18 at 21:16
  • Did that Sir. Just figured it out :) – user2823393 Mar 30 '18 at 21:17
  • 1
    How about using a pullup/pulldown resistor? When there is no connection from the input pin to any potential it will be floating – chrisl Mar 30 '18 at 22:13
1

Understanding how PULLUP works lead to the solution. Also learnt that switches are supposed to be connected to ground. Thank you all for your time. Especially chrisl.

enter image description here

  • Switches aren't "supposed" to be connected to ground. It's just that if they are you can make use of the internal pullup instead of having to attach an external pulldown. – Majenko Mar 31 '18 at 10:45
  • Don't post code as an image. – gre_gor Apr 3 '18 at 18:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.