Thus, interrupts seem to work, since an “interrupt” occurs in the event of an event. My only problem is that I interruptions will occur 2-3 times, and everything essentially stops (TV series, everything).
I programmed the board to sequentially output the calculated distance based on the IC IC-SR04 output. Distances are calculated accurately, but, as I said, everything seems to freeze. Below is the code and image of the serial monitor.

#define TRIGPIN 4 #define ECHOPIN 3 #define RED 2 #define GREEN 13 #define INTNUM 1 //interrupt pin 1 is digital pin 3 on the duemilanove #define PULSE 10 //microseconds #define CYCLETIME 50 //milliseconds void ledWrite(int), trigPulse(), getTime(); int millisNow, millisPrev = 0; int microsPrev; boolean isHigh = false; void setup() { Serial.begin (9600); pinMode(TRIGPIN, OUTPUT); pinMode(ECHOPIN, INPUT); pinMode(RED, OUTPUT); pinMode(GREEN, OUTPUT); attachInterrupt(INTNUM, getTime, CHANGE); } void loop() { trigPulse(); // some other code while waiting on HC-SR04 to interrupt us when echo goes HIGH } void trigPulse(){ if( (millisNow = millis()) - millisPrev >= CYCLETIME){ //sufficient cycle time digitalWrite(TRIGPIN, HIGH); delayMicroseconds(PULSE); digitalWrite(TRIGPIN, LOW); millisPrev = millisNow; //reset clock } return; } void ledWrite(int dTime){ int distance = dTime/58.2; if (distance < 4) { digitalWrite(RED,HIGH); digitalWrite(GREEN,LOW); } else { digitalWrite(RED,LOW); digitalWrite(GREEN,HIGH); } if (distance >= 200 || distance <= 0){ Serial.println("Out of range"); } else { Serial.print(distance); Serial.println(" cm"); } } void getTime(){ int timeNow = micros(); Serial.println("Interrupted"); if(isHigh == false){ microsPrev = timeNow; //get time now, pin LOW->HIGH isHigh = true; Serial.println("Returning .."); return; } else { //pin HIGH->lOW ledWrite(timeNow - microsPrev); isHigh = false; microsPrev = micros(); Serial.println("Returning .."); return; } return; }
source share