Showing results for 
Search instead for 
Did you mean: 
Copilot Lvl 2
Message 1 of 3

random lighting

Hi this is my first request for help, Im 72 yrs old and using arduino to turn leds on and off at random in builds on a model railroad. the code I have works fine though I would like to have one pin flicker as it comes on each time to reprosent a florecent light start up .

any help would be great.

cheers and stay well Bob 

#define numleds 8
byte ledpins [ ] = {2,3,4,5,6,7,8,9,10,11,12,13 } ;
void setup( ) {
for ( int i=1; i <= numleds; i++ ) {
pinMode ( ledpins [ i ], OUTPUT) ;
digitalWrite ( ledpins [ i ] , HIGH) ;

void loop ( ) {
digitalWrite ( ledpins [ random ( 0, numleds+1 ) ], lightsw ( ) ) ;
delay ( 2000 ) ;
boolean lightsw ( ) {

if ( random (0,100) > 60 ) return LOW ;
else return HIGH ;

2 Replies
Message 2 of 3

Re: random lighting

Hello @dadt21 

This post was moved to a different board that fits your topic of discussion a bit better. This means you’ll get better engagement on your post, and it keeps our Community organized so users can more easily find information.

As you’ll notice, your Topic is now in the Programming Help and Discussion board. No action is needed on your part; you can continue the conversation as normal here.

Let me know if you have any other questions or if I can help with anything else.

Greatly appreciated,


Mark helpful posts with Accept as Solution to help other users locate important info. Don't forget to give Kudos for great content!

Commander Lvl 2
Message 3 of 3

Re: random lighting

0. I suggest for starters you set up a separate program to work out the "flicker" mechanism before trying to incorporate it into your full program.

1. Figure out when one LED is to "flicker". I.e. not every time, not every LED.

2. In a "flicker" scenario, you want to turn that one LED on / off multiple times and with different delays.


A "flicker" might be done like so [casting my mind back to how a flourescent fixture sometimes behaves]:

- turn LED off [in case it was already on]

- turn LED on

- delay a short time (e.g. 250 ms)

- turn LED off

- delay a short time (e.g. 250 ms)

- turn LED on

- delay a longer time (e.g. 600 ms)

- turn LED off

- delay a short time (e.g. 250 ms)

- turn LED on


This tries to emulate the flash - longer flash - fullon behavior of a flakey fixture. Depending on how "flakey" you want to make it you can try different delays and/or turn the LED on/off more.


The "flicker" instructions would then become a separate function in your program. Inside the loop() you would then call the "flicker" function for an LED, depending on what random criteria you decide, suggestion below:


loop() {
int led =  random ( 0, numleds+1 ) 
if (random(0,100) > 90)
    digitalWrite ( ledpins [ led ], lightsw ( ) ) ;
delay ( 2000 ) ;


Please follow-up to let us know how you made out. For good karma, mark a reply as the answer if it helped!