Raspberry PI GPIO Scol plugin
rpishiftdriver.cpp
1
2#include "rpishiftdriver.h"
3#include "plugin.h"
4
5#include <string>
6#include <algorithm>
7#include <iostream>
8
9#include <boost/thread.hpp>
10
11#ifdef RPI
12#include <wiringPi.h>
13#include <time.h>
14#include <sys/time.h>
15#endif
16
17//
18//Class RpiShiftDriver
19//
20
21RpiShiftDriver::RpiShiftDriver()
22{
23}
24
25RpiShiftDriver::RpiShiftDriver(int data, int clock, int latch, int nbOut):
26 mData(data),
27 mClock(clock),
28 mLatch(latch),
29 mNbOut(nbOut),
30 mCurPos(0),
31 mState(false)
32{
33#ifdef RPI
34 pinMode(mData, OUTPUT);
35 pinMode(mClock, OUTPUT);
36 pinMode(mLatch, OUTPUT);
37
38 digitalWrite(mData, LOW);
39 digitalWrite(mClock, LOW);
40 digitalWrite(mLatch, LOW);
41#endif
42}
43
44RpiShiftDriver::~RpiShiftDriver()
45{
46#ifdef RPI
47 if (mState)
48 {
49 mState = false;
50 mThread.join();
51 }
52
53 WriteValue(0);
54
55 digitalWrite(mData, LOW);
56 digitalWrite(mClock, LOW);
57 digitalWrite(mLatch, LOW);
58#endif
59}
60
61void RpiShiftDriver::threadLoop()
62{
63#ifdef RPI
64 while (mState)
65 {
66 if (mCurPos >= mValues.size())
67 mCurPos = 0;
68
69 WriteValue(mValues[mCurPos].first);
70
71 // Wait until the end of the time period
72 boost::this_thread::sleep_for(boost::chrono::microseconds(mValues[mCurPos].second));
73 mCurPos++;
74 }
75#endif
76}
77
78void RpiShiftDriver::WriteValue(int value)
79{
80#ifdef RPI
81 int val = 0;
82 for (int i = 0; i < mNbOut; i++)
83 {
84 val = (value & (1 << i)) ? HIGH : LOW;
85 digitalWrite(mData, val);
86 digitalWrite(mClock, HIGH);
87 delayMicroseconds(1);
88 digitalWrite(mClock, LOW);
89 }
90
91 digitalWrite(mLatch, HIGH);
92 delayMicroseconds(1);
93 digitalWrite(mLatch, LOW);
94#endif
95}
96
97void RpiShiftDriver::SetValues(std::vector<shiftValue> values)
98{
99 mValues = values;
100
101#ifdef RPI
102 if (mState)
103 {
104 mState = false;
105 mThread.join();
106 }
107
108 if (mValues.size() > 1)
109 {
110 mCurPos = 0;
111 mState = true;
112 mThread = boost::thread(&RpiShiftDriver::threadLoop, this);
113 }
114 else
115 {
116 if (mValues.size() > 0)
117 WriteValue(mValues[0].first);
118 else
119 WriteValue(0);
120 }
121#endif
122}