Skip to content

Instantly share code, notes, and snippets.

@kashimAstro

kashimAstro/main.cpp

Last active Jun 27, 2019
Embed
What would you like to do?
HC_SR04 ofxgpio (untested)
#include "ofMain.h"
#include "ofAppNoWindow.h"
#include "ofxGPIO.h"
class HC_SR04{
public:
HC_SR04();
~HC_SR04();
long micros() {
struct timeval current_time;
gettimeofday(&current_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() );
}
@AnasGhrab

This comment has been minimized.

Copy link

@AnasGhrab AnasGhrab commented Jun 27, 2019

Maybe this ?

public:
   HC_SR04(){}
   ~HC_SR04(){}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.