I am trying to make an Led blink and send the status either on or of to serial monitor. I got the status display but not alternately as what I want. What I am doing wrong here.
Please Help.
const int ledPin = 13; // the pin that the LED is attached to
//int ledPin = 13; // LED connected to digital pin 13
int ledState = 0; // current state of the button
// The setup() method runs once, when the sketch starts
void setup() {
// initialize the digital pin as an output:
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
// the loop() method runs over and over again,
// as long as the Arduino has power
void loop() {
ledState = digitalRead(ledPin);
if (ledState == HIGH){
Serial.println("on");
}
else if (ledState == LOW );{
Serial.println("off");
}
{
digitalWrite(ledPin,LOW); // set the LED off
delay(1000); // wait for a second
digitalWrite(ledPin, HIGH); // set the LED on
delay(1000); // wait for a second
}
}
const int ledPin = 13; // the pin that the LED is attached to
int ledState = 0; // current state of the button
void setup() {
// initialize the digital pin as an output:
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
ledState = digitalRead(ledPin);
if (ledState == HIGH){
Serial.println("on");
}
else if (ledState == LOW );
In the line of code above, the semi-colon after the closing parentheses terminates the if. Which means off is printed every time through the loop. The semi-colon should be removed.
{
Serial.println("off");
}
The braces around the code below aren't harmful but they serve no useful purpose.
{
digitalWrite(ledPin,LOW); // set the LED off
delay(1000); // wait for a second
digitalWrite(ledPin, HIGH); // set the LED on
delay(1000); // wait for a second
}
}
void loop() {
ledState = digitalRead(ledPin);
if (ledState == HIGH){
Serial.println("on");
}
else if (ledState == LOW );{
Serial.println("off");
}
{
digitalWrite(ledPin,LOW); // set the LED off
delay(1000); // wait for a second
digitalWrite(ledPin, HIGH); // set the LED on
delay(1000); // wait for a second
}
}
If you go through the program, it first checks the state of ledPin, and prints the value, high or low.
You then set ledPin low, wait, set ledPin high, and then wait again.
The problem comes because you are setting ledPin low then high each time. This means that each time the loop starts after the first iteration, ledPin will always be high (as that was the last state setting).