SR04 Something is wrong(Totally solved)


the module work, got working newping library before posting this. code detect sort of distance, multiple of 172.41 not centimeter. know hick wrong 1 feel helping bit.

code: [select]


#define broche_trig 12
#define broche_echo 3

unsigned long last_detection = 0;
const int ping_interval = 150;

const double k_mach = 0.0029;

int duration;
double distance;

void setup() {

 attachinterrupt(1, got_echo, falling);
 
 pinmode(broche_trig, output);
 pinmode(broche_echo, input);

 serial.begin (115200);
 
}

void loop() {

 if(millis() - last_detection >= ping_interval) {
 
   digitalwrite(broche_trig, high);
   delaymicroseconds(5);
   digitalwrite(broche_trig, low);
   last_detection = millis();  
   
 }
 
}

void got_echo(){
 
    duration = millis() - last_detection ;
    distance = 0.5 * (duration / k_mach)   ;
    serial.println((string)distance + f(" cm"));

}

ah! it...

172.41 * 0.0029 = 0.499989, 1/2 of distance ping when hit thing. duration must = 1. mean time resolution not precise enogh.

ok millis() big, changed millis() micros(),

code: [select]

#define broche_trig 12
#define broche_echo 3
#define broche_piezo 8

volatile unsigned long last_detection = 0;
unsigned long last_detection2 = 0;
const int ping_interval = 150;

const double k_mach = 29.4117647;

int duration;
double distance;

void setup() {

 attachinterrupt(1, got_echo, falling);
 
 pinmode(broche_trig, output);
 pinmode(broche_echo, input);

 serial.begin (115200);
 
}

void loop() {
 
 if(millis() - last_detection >= ping_interval) {
 
   digitalwrite(broche_trig, high);
   delaymicroseconds(5);
   digitalwrite(broche_trig, low);
   last_detection = millis();  
   last_detection2 = micros();
   
 }
 
 
}

void got_echo(){
 
    duration = micros() - last_detection2 ;
    distance = (0.5  *(duration / k_mach)) - 8  ; // - 8 ???
    serial.println((string)distance + f(" cm"));

}



i don't why need "- 8", work:


Arduino Forum > Using Arduino > Sensors > SR04 Something is wrong(Totally solved)


arduino

Comments

Popular posts from this blog

opencv3, tbb and rasp pi 2 - Raspberry Pi Forums

small ethernet problem - Raspberry Pi Forums

Multithumb configuration params not working? - Joomla! Forum - community, help and support