Last active
June 27, 2019 18:33
-
-
Save kashimAstro/41662bd8d78246efb1820a210c7c3e60 to your computer and use it in GitHub Desktop.
HC_SR04 ofxgpio (untested)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "ofMain.h" | |
#include "ofAppNoWindow.h" | |
#include "ofxGPIO.h" | |
class HC_SR04{ | |
public: | |
HC_SR04(); | |
~HC_SR04(); | |
long micros() { | |
struct timeval current_time; | |
gettimeofday(¤t_time, NULL); | |
return current_time.tv_sec * (int)1e6 + current_time.tv_usec; | |
} | |
void setup(int trigger, int echo) { | |
this->trigger = trigger; | |
this->echo = echo; | |
pio[0].setup(trigger, OUT, LOW); | |
pio[1].setup(echo, IN, LOW); | |
usleep(5000); | |
} | |
double distance(int timeout) { | |
usleep(100); | |
pio[0].set(HIGH); | |
usleep(10); | |
pio[0].set(LOW); | |
now = micros(); | |
while (pio[1].get() == LOW && (micros()-now) < timeout); | |
update(); | |
travel_time_usec = end_time_usec - start_time_usec; | |
distance_meters = 100*((travel_time_usec/1000000.0)*340.29)/2; | |
return distance_meters; | |
} | |
void exit(){ | |
pio[0].close(); | |
pio[1].close(); | |
} | |
private: | |
void update() { | |
start_time_usec = micros(); | |
while (pio[1].get() == HIGH ); | |
end_time_usec = micros(); | |
} | |
GPIO pio[2]; | |
int trigger; | |
int echo; | |
volatile long start_time_usec; | |
volatile long end_time_usec; | |
double distance_meters; | |
long travel_time_usec; | |
long now; | |
}; | |
class no_window : public ofBaseApp{ | |
public: | |
HC_SR04 hc; | |
int trigger = 0; // change this value con pin number for trigger | |
int eco = 0; // change this value con pin number for echo | |
void setup() { | |
hc.setup(trigger,eco); | |
} | |
void update() { | |
std::cerr << hc.distance(30000) << std::endl; | |
} | |
void exit() { | |
hc.exit(); | |
} | |
}; | |
int main( ){ | |
ofAppNoWindow window; | |
ofSetupOpenGL(&window, 0,0, OF_WINDOW); | |
ofRunApp( new no_window() ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Maybe this ?