1

I have made this If-Then-Else code, but it doesn't work.

First I tough only the analog code is wrong, but if I take a digital port, the code doesn't work either.

What did I do wrong?

int sensorPin = A0;    // select the input pin for the potentiometer
int sensorValue = 0.00001;  // variable to

void setup() {
  pinMode(13, OUTPUT);  //LED BORD UIT
  pinMode(12, OUTPUT);  //LED4
  pinMode(11, OUTPUT);  //LED3
  pinMode(10, OUTPUT);  //LED2
  pinMode(9, OUTPUT);   //LED1
  pinMode(8, OUTPUT);   //Elektro Magneet
  pinMode(A0, INPUT);
}

void loop() {
  if (A0 == HIGH) {
     digitalWrite(13, LOW); 
     digitalWrite(12, HIGH);   //LED on, magnet off
     digitalWrite(11, HIGH);   
     digitalWrite(10, HIGH);   
     digitalWrite(9, HIGH);
     digitalWrite(8, LOW);     

  } else {    
     digitalWrite(13, LOW); 
     digitalWrite(12, LOW);   // LED Off, magnet on
     digitalWrite(11, LOW);   
     digitalWrite(10, LOW);   
     digitalWrite(9, LOW);      
     digitalWrite(8, HIGH);     
  }
}

migrated from electronics.stackexchange.com Oct 24 '14 at 23:35

This question came from our site for electronics and electrical engineering professionals, students, and enthusiasts.

  • Sidenote: Be careful with that electro magnet. Those tend to use quite a bit of current, while the digital pins of the arduino can only source a maximum of 40mA. You don't want to "blow up" you Arduino. – Gerben Oct 25 '14 at 13:15
  • To add to what @Gerben said, you'll want to keep current around and under 20mA on any I/O pin and under 100mA on the MCU. Beyond lighting a few LEDs, you'll have to use transistors, darlingtons and relays. – Ricardo Oct 25 '14 at 15:50
9

Replace the line:

  if (A0 == HIGH) {

by this one:

  if (digitalRead(A0) == HIGH) {

If you plan on using the pin back as an analog input, use something like this:

  if (analogRead(A0) > 512) {

The explanation is what Ignacio said: you were comparing the pin "name" A0 directly to HIGH instead of reading from the input named A0. To make it clearer, the two lines are equivalent:

if (A0 == HIGH)
if (0 == HIGH)

Get it?

There's more about what pin names to use with digitalRead() and analogRead() here:

2

You're comparing the pin variable value with HIGH. If you want to get the value at a digital input then you need to use digitalRead().

2

You have defined your pin as

int sensorPin = A0;

Which should be replaced with

#define sensorPin = A0

And then in your code, you need to read the value from the pin in your if statement:

 if (digitalRead(sensorPin) == HIGH) {

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy