Project

General

Profile

Raspberry PI GPIO Scol plugin
rpiecho.cpp
1
2#include "rpiecho.h"
3#include "plugin.h"
4
5#include <boost/thread.hpp>
6
7#ifdef RPI
8#include <wiringPi.h>
9#include <stdio.h>
10#include <stdlib.h>
11#endif
12
13//
14//Class RpiEcho
15//
16
17RpiEcho::RpiEcho()
18{
19}
20
21RpiEcho::RpiEcho(int triggerpin, int echopin):
22 mTriggerPin(triggerpin),
23 mEchoPin(echopin),
24 mValue(0),
25 mState(false)
26{
27#ifdef RPI
28 pinMode(mTriggerPin, OUTPUT);
29 pinMode(mEchoPin, INPUT);
30 digitalWrite(mTriggerPin, LOW);
31
32 mState = true;
33
34 /*boost::thread::attributes attrs;
35 struct sched_param param;
36 param.sched_priority = 50;
37 pthread_attr_setschedparam(attrs.native_handle(), &param);
38 */
39
40 mThread = boost::thread(/*attrs,*/ boost::bind(&RpiEcho::threadLoop, this));
41#endif
42
43}
44
45RpiEcho::~RpiEcho()
46{
47#ifdef RPI
48 if (mState)
49 {
50 mState = false;
51 mThread.join();
52 }
53 digitalWrite(mTriggerPin, LOW);
54#endif
55}
56
57long RpiEcho::pulseIn(int timeout)
58{
59#ifdef RPI
60 long startTime = micros();
61 long stopTime = 0;
62
63 while (digitalRead(mEchoPin) == LOW && mState)
64 {
65 if ((micros() - startTime) > timeout)
66 return 0;
67 }
68 startTime = micros();
69
70 stopTime = micros();
71 while (digitalRead(mEchoPin) == HIGH && mState)
72 {
73 stopTime = micros();
74 if ((stopTime - startTime) > timeout)
75 return 0;
76 }
77
78 return stopTime - startTime;
79#else
80 return 0;
81#endif
82}
83
84void RpiEcho::threadLoop()
85{
86#ifdef RPI
87 int timeout = 116000; // (limit to 20/2 meter for best result)
88 long avg = 0;
89 unsigned int nbacc = 0;
90 unsigned int spent = 0;
91
92 while (mState)
93 {
94 avg = 0;
95 nbacc = 0;
96
97 for (nbacc = 0; nbacc < 10;)
98 {
99 digitalWrite(mTriggerPin, LOW);
100 delay(5);
101 digitalWrite(mTriggerPin, HIGH);
102 delayMicroseconds(10);
103 digitalWrite(mTriggerPin, LOW);
104
105 spent = pulseIn(timeout);
106 if (spent == 0)
107 continue; //timeout
108
109 avg += spent; //to millisecond
110 nbacc++;
111 }
112
113 {
114 boost::mutex::scoped_lock l(mMutex);
115 if (nbacc > 0)
116 mValue = (avg / nbacc) / 58; // concert time to cm
117 }
118 }
119#endif
120}
121
122int RpiEcho::ReadValue()
123{
124 boost::mutex::scoped_lock l(mMutex);
125 return mValue;
126}