You know what? Millis timers are hard for us beginners. I've done the tutorials and read the posts but I still have trouble getting a Millis timer to trigger an event.
I want to light up an LED on pin 13 ( and also pulse a motor relay) for the duration specified in an array. The array is indexed by the button on pin 7. This works fine for one cycle. But at the end of that millis timer - let's say array item 4 which is 500 milliseconds, I want to turn off the LED, wait for trigger input from pin 6. When that pin goes LOW, wait 1000 (for the motor to spin down) and light the LED on 13. And repeat. The pin 6 trigger is an external programmable camera timer which fires the camera and triggers pin 6 every x seconds.
My code is probably a sloppy mess but if anybody is willing to wade through it, I would greatly appreciate it. Thanks.
#include <LiquidCrystal.h>
//Sketch to create an adjustable blink pattern on an LED and relay.
//ON and OFF values selected from an array via a button on 7 and from an external timer on 6.
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
unsigned long previousMillis; // will store last time LED was updated
unsigned long peg;
const int ledPin = 13; // also relay connected here
const int buttonPin = 7;
const int triggerPin = 6;
int increment[] = {
100, 200, 300, 400, 500, 600, 700, 800, 1000}; // LED on times
int lastButton; // saves the button state
int buttonState;
int triggerState;
int lastTrigger;
int buttonPresses = 4;
void setup() {
pinMode(ledPin,OUTPUT);
pinMode(buttonPin,INPUT_PULLUP);
pinMode(triggerPin,INPUT_PULLUP);
lcd.begin(16,2);
lcd.print("Motor: ");
buttonState = digitalRead(buttonPin);
triggerState = digitalRead(triggerPin);
peg = millis();
digitalWrite(ledPin,HIGH); // start off with the LED on
}
void loop() {
if (buttonPresses >= 9) // reset buttonpresses counter at 9 to 0
{
buttonPresses = 0;
}
lcd.setCursor(11,0);
lcd.print(increment[buttonPresses]);
lcd.print(" ");
int lastButton = digitalRead(buttonPin);
if (lastButton != buttonState) { // the button state has changed
if (lastButton == LOW) { // check if the button is pressed
buttonPresses++; // increment the buttonPresses variable
}
}
buttonState = lastButton;
//start millis timer and correct processing timing error
unsigned long currentMillis = millis() - ((millis() - peg) % 100);
if((currentMillis - previousMillis) >= increment[buttonPresses])
{
// save the last LED-off time
previousMillis = currentMillis;
digitalWrite(ledPin, LOW);
}
int triggerState = digitalRead(triggerPin);
unsigned long triggerStart = millis();
if (lastTrigger != triggerState) {
if (triggerState == LOW) {
if (millis() - triggerStart > 1000)
{
digitalWrite(ledPin, HIGH);
}
}
}
triggerState = lastTrigger;
}