Tilt sensor and pull up resistor

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);

No, it has to do with your description of how the tilt sensor operates. Test your assumption using a digital volt-Ohmeter to measure the resistance of the sensor connections when the sensor is upright and when it is tilted.
I think you will discover the switch contacts are open when NOT tilted and closed when tilted. At least that is how my device works.

From your description you have wired it up so that the default is a High and when the switch closes then the pin will go LOW.

But's that's a guess without the other things.

No, it is activated with pinMode(sensorpin, INPUT) and digitalWrite(sensorpin, HIGH).

When the ball contacts, the pin is pulled LOW.

Or less cryptically pinMode(senspin, INPUT_PULLUP);

So you are saying you did not actually read the OP before you jumped in? :roll_eyes:

Such as maybe, the second paragraph? :crazy_face:

That's what I typed, using INPUT_PULLUP (not just INPUT).

Which would make any read on the Pin HIGH, with the switch open, and to cause a state change on the pin, a LOW, the switch closing to ground would be needed, right?

But if the switch is wired to go HIGH when the switch closes, and the Pin is set for an input pull up, then the state change will be HIGH to HIGH or NONE, right?

Yeah, whatever! :roll_eyes: