Project

General

Profile

Raspberry PI GPIO Scol plugin
rpipin.cpp
1#include "rpipin.h"
2#include "plugin.h"
3
4#include <string>
5#include <algorithm>
6#include <iostream>
7
8#include <boost/thread.hpp>
9
10#ifdef RPI
11#include <wiringPi.h>
12#include <softPwm.h>
13#endif
14
15//
16//Class RpiPin
17//
18
19RpiPin::RpiPin()
20{
21}
22
23RpiPin::RpiPin(int pin, int mode):
24 mPin(pin),
25 mMode(mode),
26 mState(false),
27 mSoftValue(0)
28{
29#ifdef RPI
30 if (mMode == PWM_OUTPUT && mPin != 18)
31 {
32 softPwmCreate(mPin, 0, 100);
33 }
34 else if (mMode == SOFT_DIGITAL_INPUT)
35 {
36 mState = true;
37 mThread = boost::thread(&RpiPin::threadLoop, this);
38 }
39 else
40 {
41 pinMode(mPin, mode);
42 }
43#endif
44}
45
46RpiPin::~RpiPin()
47{
48#ifdef RPI
49 if (mState)
50 {
51 mState = false;
52 mThread.join();
53 }
54
55 if (mMode == PWM_OUTPUT && mPin != 18)
56 {
57 softPwmStop(mPin);
58 }
59 else if (mMode == PWM_OUTPUT)
60 {
61 pwmWrite(mPin, 0);
62 }
63
64 if (mMode == OUTPUT || mMode == PWM_OUTPUT)
65 {
66 digitalWrite(mPin, 0);
67 }
68#endif
69}
70
71void RpiPin::threadLoop()
72{
73 int NUMREADINGS = 30;
74
75#ifdef RPI
76 while (mState)
77 {
78 int value = 0;
79 for (int i = 0; i < NUMREADINGS && mState; i++)
80 {
81 pinMode(mPin, OUTPUT);
82 digitalWrite(mPin, LOW);
83 delay(10);
84
85 int c = 0;
86 pinMode(mPin, INPUT);
87 while (digitalRead(mPin) == LOW && mState)
88 {
89 delayMicroseconds(1);
90 c++;
91 }
92 value += c;
93 }
94
95 mSoftValue = value / NUMREADINGS;
96 boost::this_thread::sleep_for(boost::chrono::milliseconds(16));
97 }
98#endif
99}
100
101void RpiPin::SetPullUpDnControl(int mode)
102{
103#ifdef RPI
104 pullUpDnControl(mPin, mode);
105#endif
106}
107
108void RpiPin::DigitalWrite(int value)
109{
110#ifdef RPI
111 digitalWrite(mPin, value);
112#endif
113}
114
115int RpiPin::DigitalRead()
116{
117#ifdef RPI
118 return digitalRead(mPin);
119#else
120 return 0;
121#endif
122}
123
124void RpiPin::AnalogWrite(int value)
125{
126#ifdef RPI
127 if (mMode == PWM_OUTPUT)
128 {
129 if (mPin != 18)
130 {
131 softPwmWrite(mPin, value);
132 }
133 else
134 {
135 pwmWrite(mPin, value);
136 }
137 }
138 else
139 analogWrite(mPin, value);
140#endif
141}
142
143int RpiPin::AnalogRead()
144{
145#ifdef RPI
146 if (mMode == SOFT_DIGITAL_INPUT)
147 {
148 return mSoftValue;
149 }
150 else
151 {
152 return analogRead(mPin);
153 }
154#else
155 return 0;
156#endif
157}
158
159void RpiPin::PwmWrite(int value)
160{
161 if (value < 0)
162 value = 0;
163 else if (value > 1023)
164 value = 1023;
165
166#ifdef RPI
167 if (mPin != 18)
168 {
169 softPwmWrite(mPin, value);
170 }
171 else
172 {
173 pwmWrite(mPin, value);
174 }
175#endif
176}