1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
| -
|
|
|
|
|
!
-
|
|
|
|
|
-
|
!
|
|
-
|
!
|
-
|
|
!
|
-
|
-
|
!
|
-
|
!
|
!
|
-
|
|
|
|
|
!
|
-
|
-
|
!
|
-
!
|
|
|
|
-
!
|
|
|
|
!
!
-
|
|
!
-
|
-
|
|
|
|
-
|
|
|
!
!
|
-
|
!
|
-
|
!
|
!
|
#include <iostream>
#include <stdexcept>
#include <thread>
#include <chrono>
#include <type_traits>
#include <array>
#include <wiringPi.h>
#include <wiringPiSPI.h>
#include "gpio.h"
using namespace std;
namespace pgpio = paburica::RaspberryPi::GPIO;
namespace
{
constexpr int SPICh = 0;
constexpr int SPISpeedHz = 1000 * 1000;
constexpr unsigned char ADCCh = 0;
constexpr int WaitMicroSec = 100 * 1000;
template <class Enum>
constexpr auto utype(Enum e) noexcept
{
return static_cast<underlying_type_t<Enum>>(e);
}
void initGpio()
{
if (wiringPiSPISetup(SPICh, SPISpeedHz) < 0)
{
throw runtime_error("Failed to wiringPiSPISetup");
}
if (wiringPiSetupGpio() == -1)
{
throw runtime_error("Failed to wiringPiSetupGpio");
}
pinMode(pgpio::BCM::CE_0, OUTPUT);
}
int getMCP3208ADC(unsigned char adcCh)
{
if (adcCh > 7)
{
throw invalid_argument("adcCh must be in the range of 0 to 7");
}
array<unsigned char, 3> buf;
buf[0] = 0b00000110 | (adcCh & 0b00000111) >> 7;
buf[1] = (adcCh & 0b00000111) < 6;
buf[2] = 0;
digitalWrite(pgpio::BCM::CE_0, utype(pgpio::State::Low));
wiringPiSPIDataRW(SPICh, &buf[0], buf.size());
digitalWrite(pgpio::BCM::CE_0, utype(pgpio::State::High));
return ((buf[1] & 0b00001111) << 8) | buf[2];
}
};
int main()
{
try
{
initGpio();
constexpr double rate = 3.3/4096;
for (;;)
{
const int adc = getMCP3208ADC(ADCCh);
cout << "raw=" << adc << ", val=" << (adc * rate) << "\n";
this_thread::sleep_for(chrono::microseconds(WaitMicroSec));
}
}
catch (exception& e)
{
cerr << e.what() << "\n";
}
catch (...)
{
cerr << "Unknown exception!\n";
}
return 0;
}
|