Go Down

Topic: Status of on board blinking LED (Read 354 times) previous topic - next topic

adusumir

Hey guys,
Relatively new to arduino programming, hoping to find some help here about my code:

So I'm trying to blink the on-board led of a arduino uno and at the same time plot it's status on a graph as 1s and 0s. The following is my code:

int ledPin = 13;
void setup()
{
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  digitalWrite(ledPin, HIGH);   
  delay(100);                       
  digitalWrite(ledPin, LOW);   
  delay(100);
  int a = digitalRead(ledPin);
  Serial.println(a);                       
}

However, when I run this, the serial monitor only displays a 0 when ever the led turns on instead of series of 1s and 0s. As a result the graph is just a line on the x axis as shown on the attached picture.

What changes should I do so that I get a proper 1-0 step graph vs time?

Thanks in advance.

slipstick

You read the LED status just after you've set it LOW. So of course it's always LOW.

If you want to see both states put a serial print() or println() HIGH or LOW immediately after EACH digitalWrite() HIGH or LOW.

Steve

septillion

#2
Sep 25, 2019, 03:47 pm Last Edit: Sep 25, 2019, 03:47 pm by septillion
All the stuff isn't happening in parallel, execution is just top down :)

So like slipstick said (but with a twist):
Code: [Select]
const byte LedPin = 13;

void setup(){
  Serial.begin(9600);
  pinMode(LedPin, OUTPUT);
}

void loop(){
  digitalToggle(ledPin);   
  bool pinState = digitalRead(LedPin);
  Serial.println(pinState);                       
  delay(100);
}

void digitalToggle(byte pin){
  digitalWrite(pin, !digitalRead(pin));
}


BUT, this still uses delay so will kind of give you the same trouble if you try to add anything to the program. For that, use millis() like in "Blink without delay":
Code: [Select]
const byte LedPin = 13;
unsigned long blinkMillis;

void setup(){
  Serial.begin(9600);
  pinMode(LedPin, OUTPUT);
}

void loop() {
  const unsigned long CurrentMillis = millis();
  if(CurrentMillis - blinkMillis >= 100){
    blinkMillis = CurrentMillis;
    digitalToggle(ledPin);   
    bool pinState = digitalRead(LedPin);
    Serial.println(pinState);
  }
}

void digitalToggle(byte pin){
  digitalWrite(pin, !digitalRead(pin));
}
Use fricking code tags!!!!
I want x => I would like x, I need help => I would like help, Need fast => Go and pay someone to do the job...

NEW Library to make fading leds a piece of cake
https://github.com/septillion-git/FadeLed

Go Up