Hi,
I’m totally new to arduino and looking for some help.
I’m looking to build an IR object counter for a production line. It produces 180 pieces per minute and want the counter to tell me every 60 seconds how many pieces have passed.
That way I can know if the line is running below target speed.
Check out the documentation for millis().. It returns the time since the Arduino started running in milliseconds.
Mark the millis() value when the program starts and count to 6000, that's 60 seconds. Report whatever count you have. Reset the counter to zero, mark the millis() and start again.
Good luck.
const unsigned long REPORT_INTERVAL = (1000 * 60); // seconds
unsigned long timer;
const int IR_PIN = 8;
int counter = 0;
void setup() {
Serial.begin(9600);
Serial.println("Starting ...");
pinMode(IR_PIN, INPUT);
// mark time
timer = millis();
}
void loop() {
// if object is passing sensor
if ( digitalRead(IR_PIN) == LOW )
{
// wait for it to pass
counter += waitForObject();
} // if
// time to report?
if ( millis() - timer >= REPORT_INTERVAL )
{
// print count
Serial.print("Count = ");
Serial.println(counter);
// reset
counter = 0;
timer = millis();
} // if
}
int waitForObject()
{
// while object is still passing
while ( digitalRead(IR_PIN) == LOW );
return 1;
}
Edit: thanks blh64, changed 6 => 60.
Edit 2: interval needs to be unsigned long due to edit 1
The only way this code con not report anything is if IR_PIN is constantly LOW. This will cause the program to wait forever inside waitForObject(). May read the value and print it out as a start?
Use unsigned long for your time elements.
That is what millis() and micros() return.
With millis(), numbers returned will be from 0 right after a restart, uo to 2^32 - 1 if you run the program for 49+ days.
Then it rolls over back to 0 and keeps on going.
if (millis() - lastReport >= reportInterval)
{
Serial.print(" Last minute:");
Serial.println(counter);
counter = 0;
lastReport = millis();
}
}//loop
Thanks Evadne! This is exactly what I was looking for. Only problem is I realised my IR sensor is not digital but analog. I simulated it by pulling the wire in and out of PIN 8 and it works great.
How can I change the code to work with an analog IR sensor? Or can I better buy a digital sensor?