I have tried this below code for ON a random LED at a time but in this below code on the basis of random number but all LEDs are ON but no one is OFF. How can I OFF the LED ?
const int led_pin[9] = {2, 3, 4, 5, 6, 7, 8, 9, 10};
const long Interval = 1000;
unsigned long previousMillis = 0;
int randNum;
void setup()
{
Serial.begin(9600);
for (int i = 0; i <= 8; i++)
{
pinMode(led_pin[i], OUTPUT);
}
}
void loop()
{
randNum = random(9);
unsigned long currentMillis = millis();
led_on(currentMillis, randNum);
}
void led_on(unsigned long currentMillis, int pinNum)
{
if (currentMillis - previousMillis >= Interval)
{
previousMillis = currentMillis;
digitalWrite(led_pin[pinNum], HIGH);
Serial.println(pinNum);
}
}
It reads like it should work and Arduino is so fast that the set high or low for-loop may run in a few microseconds. Using direct port methods, about 1 microsecond.
Suppose that void led_on() kept a saved value of which pin is ON
static byte on_pin; // pin turned ON last
then when time runs out,
digitalWrite( on_pin, LOW );
on_pin = pinNum; // the next pin to turn ON
digitalWrite( on_pin, HIGH );
Since on;y 1 led is on, only 1 needs turned off
The next led gets turned on, 2 digitalWrite( Arduino safe ) instead of 8.
Do you want to work the pins through the pin registers for speed you don't need?
@GoForSmoke
I cannot understand properly. I mean I understand what you want say but that example I cannot understand properly. can you please write the perfect example ? where I need to change that think ? can you please help. or if you don't mind then can you please give whole code or function.