-1

Newbie here - literally opened my Arduino about 3 hours ago. I have been able to code 2 LEDs to blink randomly, but what I want to do is have one of the two blink every 10 seconds.

My current code:

void setup() {
  pinMode(4, OUTPUT); 
  pinMode(5, OUTPUT); 
}

void loop() {
  // set 2 random on/off values
  byte on4 = random(2); //returns a random choice of 0 or 1
  byte on5 = random(2);

  //Write the value of each variable to the pins.
  digitalWrite(4,on4);
  digitalWrite(5,on5);
  delay(500); 
}

I know I have to do something to the loops, I just can't figure out what.

4

Try out this code. It will helpful.

const int kPinLed = 4;      // LED at pin 4

void setup()
{
  pinMode(kPinLed, OUTPUT); // LED as OUTPUT
}

void loop()
{
  digitalWrite(kPinLed, HIGH); // LED ON
  delay(10000);                // 10 Sec delay
  digitalWrite(kPinLed, LOW);  // LED OFF
  delay(10000);                // 10 Sec delay
}
0

Choose if you want to keep pin 4 or 5. Remove every reference to the other.

Move the declaration of the remaining pin outside of the loop, before the setup function. Ex: byte on4;

inside setup, assign a value (1 or 0) to the surviving pin. Ex: on4 = 0;

inside the loop, change the value of the pin. EX: on4 = !on4;

digitalWrite changes the state of the pins driving the LEDs. Remove the one you do not want.

delay expresses how long the system waits, in milliseconds. Change accordingly.

byte on4;

void setup() {
  on4 = 0;
  pinMode(4, OUTPUT); 
}

void loop() {;
  on4 = !on4;
  digitalWrite(4,on4);
  delay(10000); 
}

This should work, but I have not tested it.

0

You need to split the logic into 2 parts. One part will select the pin that you want to blink and the other will blink the pin. I'll show how you do this using delay() but, clearly, it would be better to use the BlinkWithoutDelay methods of counting time so the processor can do something else. This code is untested and is set up so that you can just add pins to the ledPin array with no other changes and it will always work properly.

uint8_t ledPin[] = { 4, 5 };  // Arduino pins with the LEDs

#define ARRAY_SIZE(a) (sizeof(a)/sizeof(a[0]))

void BlinkOne(uint8_t pin)
{
  digitalWrite(pin, HIGH);
  delay(5000);
  digitalWrite(pin, LOW);
  delay(5000);
}

void setup(void)
{
  for (uint8_t i=0; i<ARRAY_SIZE(ledPin); i++)
    setMode(ledPin[i], OUTPUT);
}

void loop(void)
{
  uint8_t thisPin = ledPin[random(ARRAY_SIZE(ledPin))];  // select which pin

  BlinkOne(thisPin);  // blink that pin
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.