I understand millis() conceptually, and I have looked at blinkwithoutdelay. I have used millis() before, but it was pulled from code that I found. I am trying to use it in a program, but I can't find examples that use it in the way I need it.
It is for a door on a hopper.
I am using a diode limit switch circuit with a DC gearmotor
electronics.stackexchange.com/questions/293726/limit-switch-on-reversing-motor
I am using a breakout board relay to control a multifunction relay from Mcmaster Carr:
I am using IR beam sensors from Adafruit:
When a ping pong ball drops into the hopper, the IR sensor will be triggered for a very short amount of time. When the hopper fills up, the sensors will be triggered indefinitely. After 2 seconds of being triggered, the door opens and empties out the hopper. The door then closes and waits for the hopper to fill up again.
I have code that will open the door whenever the sensor is triggered, but I can't get the "after 2 seconds" part to work.
For simplicity, I am only working with only 1 of the sensors:
const int trigger1 = 11;
const int trigger2 = 12;
const int relay = 4;
int trigger1val = 0;
int trigger2val = 0;
unsigned long currentmillis;
unsigned long startmillis = 0;
void setup()
{
Serial.begin(9600);
pinMode(relay, OUTPUT);
pinMode(trigger1, INPUT);
pinMode(trigger2, INPUT);
digitalWrite(trigger1, HIGH);
digitalWrite(trigger2, HIGH);
digitalWrite(relay, HIGH);
}
void loop()
{
trigger1val = digitalRead(trigger1);
trigger2val = digitalRead(trigger2);
currentmillis = millis();// record the time
if ( trigger1val == LOW)
startmillis = currentmillis;
if (currentmillis - startmillis >= 2000 && trigger1val == LOW) // is the time has passed AND the sensor
//still being triggered
{
digitalWrite(relay, LOW);// pulse the relay
delay(100);
digitalWrite(relay, HIGH);
}
else
{
digitalWrite(relay, HIGH);
}
if ( trigger2val == LOW) //this part is only pulsing the relay when the sensor is triggered
//It does not wait 2 seconds to see if the sensor is still being triggered
{
digitalWrite(relay, LOW);
delay(200);
digitalWrite(relay, HIGH);
}
else
{
digitalWrite(relay, HIGH);
}
Serial.println(trigger1val);
Serial.print("\t");
Serial.println(trigger2val);
}
I have looked at the "using millis() for timing in the forum. Helpful, but I still am doing something wrong. Any insights into what I am doing wrong will be much appreciated. Thank You.