I wrote the following program for interfacing the ultrasonic sensor using g++ in raspberry pi Raspbian wheezy, using the wiring Pi libraries.However i couldn't make it work.Is there any problem with my code??? I want a continuous reading from the sensor... Thank you in advance!!!
#include<iostream>
#include<wiringPi.h>
#include<errno.h>
#include<string.h>
#include<stdint.h> //for uint32_t
using namespace std;
uint32_t time1=0,time2=0;
int time_diff=0;
float Range_cm=0;
void myInterrupt(void)
{
cout<<"Interrupt\n";
time2=micros();
time_diff=time2-time1;
Range_cm=time_diff/58;
delay(150);
digitalWrite(2,0);
delayMicroseconds(1);
digitalWrite(2,1);
delayMicroseconds(10);
digitalWrite(2,0);
time1=micros();
}
int main(void)
{
if(wiringPiSetup()<0)
{
cout<<"wiringPiSetup failed !!\n";
}
pinMode(2,OUTPUT);
pinMode(3,INPUT);
pullUpDnControl(3,PUD_DOWN);
digitalWrite(2,0);
delayMicroseconds(1);
digitalWrite(2,1);
delayMicroseconds(10);
digitalWrite(2,0);
time1=micros();
if(wiringPiISR(3,INT_EDGE_RISING,&myInterrupt) < 0)
{
cerr<<"interrupt error ["<<strerror (errno)<< "]:"<<errno<<endl;
return 1;
}
while(1)
{
cout<<"distance= "<<time1<<" "<<time2<<" "<<time_diff<<" "<<Range_cm<<"cm\n";
cout.flush();
}
return 0;
}
myInterrupt
function really running from a hardware interrupt? Interrupt functions should be simple and fast. Having delays in them is the opposite of fast. Preferably they just set a flag, and let the non-interrupt code check the flag and perform whatever actions needed. – Some programmer dude Mar 22 '14 at 16:27volatile
and using an atomic would be a good idea then. – πάντα ῥεῖ Mar 22 '14 at 17:34volatile int num_interrupts = 0;
. Change the body of myInterrupt to a single line of code,num_interrupts++;
. In your infinite loop inmain
, print outnum_interrupts
. Does it ever increment? If so, your problem is in your interrupt handler. If not, your problem is that your interrupt isn't happening. – indiv Mar 22 '14 at 17:37