Hi everyone, I am currently trying to make my sensor work without delay and with these parameters: sampling frequency of 100Hz using Serial.println (for testing purposes, this will serve to plot with Matlab later on) and a baudrate of 9600.
My code is here:
const int trigger = 2;
const int echo = 3;
long t;
long d;
int trigger_actual = 0;
int muestreo_actual = 0;
int pulso;
bool inicio = 1;
void setup(){
Serial.begin(9600);
pinMode(trigger, OUTPUT);
pinMode(echo, INPUT);
digitalWrite(trigger, LOW);
}
void loop(){
if(inicio == 1){
digitalWrite(trigger, HIGH);
inicio = 0;
}
if((micros() - trigger_actual) >= 10){
pulso = micros() - trigger_actual;
digitalWrite(trigger, LOW);
t = pulseIn(echo, HIGH); // Obtengo el ancho de pulso.
d = t*0.034/2; // Velocidad_sonido = 2d/t;
digitalWrite(trigger, HIGH);
trigger_actual = micros();
}
if((millis() - muestreo_actual) >= 10){
Serial.println(d);
muestreo_actual = millis();
}
}
The problem is the following:
I get coherent readings when the distance is above 20cm, below this value these get weird, and ataround 15cm the RX led turns off and I start getting zeros for an interval, same happens for 5cm (zeros for a couple seconds before getting decent readings).
It is only after a minute or so of continuous testing with my hand (moving it closer and farther from the sensor at a certain speed) that the system stabilizes and I get accurate readings.
What is wrong with my code? Thanks so much for your attention in advance.
Edit: The SensorKalman.h tab that appears in the screesnshots is for later on, doesnt matter yet.