I'm making a sort of state machine with 3 states, and I'm actually doing some tests by configuring at the start of my code state=3. I've wired on each pin 2 leds, for a total of 12 leds. I'm using elapsedMillis library (https://github.com/pfeerick/elapsedMillis) to make things a bit more easy and I'm stuck at 3rd state. At the 3rd state I would like that each couple of leds will stay on for 90ms, than goes of for 1ms. elapsedMillis library allows one to do something like that:
elapsedMillis timeElapsed; //declare global if you don't want it reset every time loop runs
#include "elapsedMillis.h"
const int pin0 = 12;
const int pin1 = 11;
const int pin2 = 10;
const int pin3 = 9;
const int pin4 = 8;
const int pin5 = 7;
unsigned long t1 = 500;
unsigned long waiting = 1000;
unsigned long t2 = 100;
unsigned long t3 = 50;
unsigned long t4 = 1;
unsigned long t5 = 90;
unsigned long startTime = 0;
int ledArray[] = {pin0, pin1, pin2, pin3, pin4, pin5};
int j, k, a, c = 0;
int state = 3;
elapsedMillis elapsedTime;
elapsedMillis timer1;
elapsedMillis timer2;
elapsedMillis timer3;
elapsedMillis timer4;
elapsedMillis timer5;
void setup() {
pinMode(pin0, OUTPUT);
pinMode(pin1, OUTPUT);
pinMode(pin2, OUTPUT);
pinMode(pin3, OUTPUT);
pinMode(pin4, OUTPUT);
pinMode(pin5, OUTPUT);
Serial.begin(9600);
}
void loop() {
switch (state) {
case 0:
// led accesi in modo scalare allo stato 0
while (k <= 5)
{
if (timer1 >= t1)
{
if (j <= 5)
{
digitalWrite(ledArray[j], HIGH);
j++;
timer1 = 0;
}
k++;
elapsedTime = 0;
}
}
// attendo 1s poi vado allo stato 1
if (elapsedTime >= waiting) {
state = 1;
elapsedTime = 0;
}
break;
case 1:
// led spenti rapidamente in modo scalare
while (k >= 0) {
if (timer2 >= t2)
{
if (j >= 0)
{
digitalWrite(ledArray[j], LOW);
j--;
timer2 = 0;
}
k--;
elapsedTime = 0;
}
}
// attendo 0.1s
if (elapsedTime >= t2) {
state = 2;
}
break;
case 2:
// led fade per 3 volte
if (c <= 3)
{
while (a <= 255)
{
if (timer3 >= t3) {
analogWrite(ledArray[3], a);
timer3 = 0;
a += 10;
}
}
while (a >= 0)
{
if (timer3 >= t3) {
analogWrite(ledArray[3], a);
timer3 = 0;
a -= 10;
}
}
c++;
}
else {
state = 3;
}
break;
case 3:
if (timer4 >= t5) {
if (j <= 5) {
digitalWrite(ledArray[j], HIGH);
j++;
timer4 = 0;
if (timer5 >= t4) {
digitalWrite(ledArray[j], LOW);
timer5 = 0;
}
}
}
break;
}
}
case 3:
for (int ii = 0; ii <= 5; ii++)
{
digitalWrite(ledArray[ii], ( (ii == j) && (timer4 < 90)));
}
if (timer4 > 91) {
j += backwardScan ? -1 : 1 ;
if (j > 5) {
backwardScan = 1;
j = 5;
}
if (j < 0) {
backwardScan = 0;
j = 0;
}
timer4 = 0;
}
break;
For the state3 I would like an effect like the "KITT" knight rider car in 80s TV show. Each couple of 2 leds should move back and forth... in shortly: first 2 leds stays on 90ms and 1ms off, then second 2 leds on 90ms and 1ms off.. etc...
It seems like the leds in the array goes on all together.