Go Down

Topic: Randomly Alternate LED pins (Read 1 time)previous topic - next topic

tekjones9 #15
May 29, 2019, 07:37 pm
The pin numbers are in an array
The array indices are 0 and 1
You need to generate a random number that is either 0 or 1 to use as the index to the array
Code: [Select]
random(0, 1);
does not generate a random number that is either 0 or 1.  Print it to see what it does generate
Well, changing it to ledPin1=myPins[random(o,2)]; which should generate a value between 0 and 1 does not actually fix the problem so what is wrong?

PaulRB #16
May 29, 2019, 08:02 pmLast Edit: May 29, 2019, 08:03 pm by PaulRB
More errors here:
Code: [Select]
ledPin1 = myPins[random(0,2)];

if(ledPin1 = 0){
int ledPin2 = 1;}
else {
int ledPin2 = 0;}

What value could ledPin1 be here? Should it ever be zero?

It's important to understand the difference between "=" and "=="

tekjones9 #17
May 29, 2019, 10:58 pm
Thank you to everyone for your helpful comments. This isn't a programming language I have used much before so the little things become frustratingly invisible.

Below is the code that achieves my desired output for any future reference:

Code: [Select]

unsigned long previousMillisLED10 = 0; //millis() returns an unsigned long
unsigned long previousMillisLED11 = 0; //millis() returns an unsigned long

unsigned long intervalLED10 = 100; //time needed to wait (ms) - 10 Hz
unsigned long intervalLED11 = 1; //1 kHz

boolean LED10State = false; //state variable for LED
boolean LED11State = false;

int ledPin1;
int ledPin2;

void setup() {
// put your setup code here, to run once
Serial.begin(9600);
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);

int myPins[]={10, 11};

ledPin1 = myPins[random(0,2)];

if(ledPin1 == 10){
ledPin2 = 11;}
else if (ledPin1 == 11){
ledPin2 = 10;}

Serial.print("Pin 1: " );
Serial.println(ledPin1);
Serial.print("Pin 2: " );
Serial.println(ledPin2);
}

void loop() {
// put your main code here, to run repeatedly:

unsigned long currentMillis = millis(); //grab current time
//toggle LED10
if ((unsigned long)(currentMillis-previousMillisLED10)>= intervalLED10){
LED10State =!LED10State; //toggles the state
digitalWrite(ledPin1, LED10State); //sets the LED based on ledState
//save the 'current' time to pin 10's previousMillis
previousMillisLED10 = currentMillis;
}
//toggle LED11
if ((unsigned long)(currentMillis-previousMillisLED11)>= intervalLED11){
LED11State =!LED11State; //toggles the state
digitalWrite(ledPin2, LED11State); //sets the LED based on ledState
//save the 'current' time to pin 11's previousMillis
previousMillisLED11 = currentMillis;
}
}

Go Up