Arduino ''if" doesn't work

My code doesn't work

int contact=0;

int switchPin = 8;

void setup() {

// put your setup code here, to run once:

pinMode(8, INPUT);

pinMode(10, OUTPUT);

}

void loop() {

contact=digitalRead(8);

if (contact == HIGH) {;

digitalWrite(10, HIGH);

}

}

[
![Schermafbeelding 2024-02-10 110134|690x259](upload://2bpNrzYQbzabP29nnahJxlwCEXc.png)

Welcome to the forum

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 < CODE/ > icon above the compose window) to make it easier to read and copy for examination

https://forum.arduino.cc/t/how-to-get-the-best-out-of-this-forum

What should it do and what does it do, if anything ?

Check your pin numbers
Then use the names you gave them.

YOur code definitly works. It does exactly what you told it to do. Question is, do you understand what you told it to do?

I fixed your post up a little.

int contact = 0;
int switchPin = 8;

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

void loop() {
  contact = digitalRead(switchPin);
  if (contact == HIGH) {
    digitalWrite(10, HIGH);
  }
}

You didn't name pin 10; I didn't make up a name for it.
Please answer this - how is your switchpin wired? Pin to button to ground, or pin to button to 5V? Is there a resistor in there somewhere?
And tell us, what does/doesn't it do? "doesn't work" covers a broad range.

buttons are typically connected between the pin and ground, the pin configured as INPUT_PULLUP to use the internal pullup resistor which pulls the pin HIGH and when pressed, the button pulls the pin LOW.

a button press can be recognized by detecting a change in state and becoming LOW

Wow!!

Although odd looking that does not affect the operation of the sketch. It's just effectively a blank line of code.

1 Like

where does the output pin get set LOW?

@bluegoat404

Ask the OP. Seriously, man?

your post had the code formatted properly

Never?

This is how the sketch performs:

note that the 'switch' input comes from a function generator and may not be representative of bloko's switch.

1 Like

He probably meant to write

if (contact == HIGH); {

Luckily he got it wrong and wrote a line of correct, if unusual, code

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