Hi I'm trying to get the hc sr04 to work with a interupt,
this code works fine up until ~ 250centimeters , I don't get any output further then that
#include <PinChangeInt.h>
const int trigPin = A1;
const int echoPin = A0;
float DistanceRaw, Distance;
int loopdone = 1, setlow, sethigh, setlow2, SonarStarted, SonarDone;
uint32_t SonarTimer, timer, SonarEchoTimer;
void SonarEcho() {
if (digitalRead(echoPin) == HIGH && setlow2 == 1 && SonarStarted == 0 && SonarDone == 0) {
SonarEchoTimer = micros();
SonarStarted = 1;
}
if (digitalRead(echoPin) == LOW && setlow2 == 1 && SonarStarted == 1) {
SonarDone = 1;
}
}
void setup() {
Serial.begin(115200);
pinMode(trigPin, OUTPUT);
PCintPort::attachInterrupt(echoPin, SonarEcho, CHANGE);
}
void loop() {
if (loopdone == 1 || micros() - SonarTimer > 150000) {
SonarTimer = micros();
SonarStarted = 0;
loopdone = 0;
setlow = 0;
sethigh = 0;
setlow2 = 0;
}
if (setlow == 0) {
digitalWrite(trigPin, LOW);
setlow = 1;
}
if (sethigh == 0 && micros() - SonarTimer > 5000) {
digitalWrite(trigPin, HIGH);
sethigh == 1;
}
if (setlow2 == 0 && micros() - SonarTimer > 10000) {
digitalWrite(trigPin, LOW);
setlow2 = 1;
}
if (SonarDone == 1) {
SonarDone = 0;
DistanceRaw = (micros() - SonarEchoTimer) * 0.034 / 2;
loopdone = 1;
setlow2 = 0;
SonarStarted = 0;
// if (DistanceRaw < 1000 && DistanceRaw > 2) {
Distance = Distance * .90 + DistanceRaw * .1;
Serial.println(DistanceRaw);
// }
}
}
and this code (wich is almost the same but without the interupt) works perfect until 500 centimeters
const int trigPin = A1;
const int echoPin = A0;
long Duration, DistanceRaw, Distance, barometerheight;
int sonar, baroset;
int loopdone, setlow, sethigh;
uint32_t timersonar, timer;
void setup() {
Serial.begin(115200);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
//Serial.println(micros() - timer);
timer = micros();
if (loopdone == 0) {
timersonar = millis();
loopdone = 1;
setlow = 0;
sethigh = 0;
}
if (setlow == 0) {
digitalWrite(trigPin, LOW);
setlow = 1;
}
if (sethigh == 0 && millis() - timersonar > 5) {
digitalWrite(trigPin, HIGH);
sethigh == 1;
}
if (millis() - timersonar > 10) {
digitalWrite(trigPin, LOW);
Duration = pulseIn(echoPin, HIGH);
DistanceRaw = (Duration * 0.034) / 2;
loopdone = 1;
if (DistanceRaw < 600 && DistanceRaw > 2) {
//Serial.print("DistanceRaw: ");
Serial.println(DistanceRaw);
Distance = DistanceRaw;
sonar = 1;
baroset = 0;
}
}
}
Does someone knows what could be wrong (sorry for the unselfexplanitory code)