Arduino Completely Freezes After a Few Minutes

Hi there,

I’m running an Arduino Uno R3 with this code:



#define trigPin1 6

#define echoPin1 7

#define trigPin2 8

#define echoPin2 12

int hit1 = 0, hit2 = 0;

int numEntries = 0, numExits = 0;

#include <LiquidCrystal.h>

LiquidCrystal lcd(11,10,9,2,3,4,5);

void setup() {

Serial.begin(9600);

lcd.begin(16, 2);

lcd.print(“Persons:”);

pinMode(trigPin1, OUTPUT);

pinMode(echoPin1, INPUT);

pinMode(trigPin2, OUTPUT);

pinMode(echoPin2, INPUT);

pinMode(13,OUTPUT);

}

void loop() {

lcd.setCursor(0, 1);

int duration, distance;

digitalWrite(trigPin1, LOW);

delayMicroseconds (60);

digitalWrite (trigPin1, HIGH);

delayMicroseconds (60);

digitalWrite (trigPin1, LOW);

duration = pulseIn (echoPin1, HIGH);

distance = (duration/2) / 29.1;

if(distance < 50){

Serial.println(“Entering…”);

hit1 = 1;

}

int duration2, distance2;

digitalWrite(trigPin2, LOW);

delayMicroseconds (60);

digitalWrite (trigPin2, HIGH);

delayMicroseconds (60);

digitalWrite (trigPin2, LOW);

duration2 = pulseIn (echoPin2, HIGH);

distance2 = (duration2 / 2) / 29.1;

if(distance2 < 50){

Serial.println(“Exitting…”);

hit2 = 1;

}

while(hit1 == 1 && hit2 == 0){

int dur, dist;

digitalWrite(trigPin2, LOW);

delayMicroseconds (60);

digitalWrite (trigPin2, HIGH);

delayMicroseconds (60);

digitalWrite (trigPin2, LOW);

dur = pulseIn (echoPin2, HIGH);

dist = (dur / 2) / 29.1;

if(dist < 50){

hit1 = 0;

hit2 = 0;

numEntries++;

Serial.println(“\tENTERED”);

delay(250);

break;

}

}

while(hit1 == 0 && hit2 == 1){

int dur, dist;

digitalWrite(trigPin1, LOW);

delayMicroseconds (60);

digitalWrite (trigPin1, HIGH);

delayMicroseconds (60);

digitalWrite (trigPin1, LOW);

dur = pulseIn (echoPin1, HIGH);

dist = (dur / 2) / 29.1;

if(dist < 50){

hit1 = 0;

hit2 = 0;

numExits++;

Serial.println(“\tEXITED”);

delay(250);

break;

}

}

lcd.print(numEntries - numExits);

if(numEntries - numExits > 0) digitalWrite(13,HIGH); else digitalWrite(13,LOW);

/*lcd.begin(16,2);

lcd.clear();

lcd.setCursor(0, 0);

lcd.print(“Persons:”);

lcd.print(numEntries - numExits);

*/

delay(50);

}



It counts the number of people in the room and turns on a light accordingly.

It works great except it just freezes after I pass through the sensors a few times. Sometimes only 3 times before it freezes, sometimes 20.

What do I need to do to fix this problem?

Thanks in advance.

Could it be that the actual Arduino Uno is defective?

So. The culprit was found. If I trigger both the ultrasound sensors at the same time.

Then it will not work because they are both waiting for the other one to become triggered.

How do I fix this?

How do I incorporate a line of code that will reset the code if the second sensor is not triggered within 2 seconds of the first.