Hi! Can someone please help explain what is going on exactly in my circuit, with my code? I have a simple circuit with 1 LED, and a tilt ball sensor. I did not put in a resistor in the tilt ball sensor circuit (so just one wire to ground, the other to digital pin).
I understand that I can activate the internal pull-up resistor in the board by using INPUT_PULLUP in pinMode, or by using digitalWrite(sensorpin, OUTPUT). From what I understand, a pull up resistor will initialize the digital pin to a HIGH value (so it's not floating).
My question is, with the code below, my LED turns on when the sensor is tilted (ie, the balls are not touching the metal connections), and the LED turns off when the sensor is straight (ie the balls are touching the metal connections).
But, the code is saying when the value is HIGH (ie balls are touching metal connections), then turn the LED on.
Why is the opposite happening? I have a feeling it has to do with the pull up resistor.
Thanks in advance! Here's the code (ps I know this code can be simplified, but I am using it for training purposes so therefore it's written very explicity).
int sensorpin = 4;
int ledpin = 7;
void setup() {
// put your setup code here, to run once:
pinMode(sensorpin, INPUT_PULLUP);
pinMode(ledpin, OUTPUT);
//digitalWrite(sensorpin, HIGH);
}
void loop() {
// put your main code here, to run repeatedly:
int sensorval = digitalRead(sensorpin);
if(sensorval == HIGH){
digitalWrite(ledpin, HIGH);
}
else {
digitalWrite(ledpin, LOW);
}
}