API
 
Loading...
Searching...
No Matches
MCP3208.cpp
Go to the documentation of this file.
1#include "MCP3208.h"
2#include <cstdint>
3#include "lgpio.h"
4#include <stdexcept>
5
6namespace MCP3208Lib {
7
9 const int dev,
10 const int channel,
11 const int baud,
12 const int flags) noexcept :
13 _handle(-1),
14 _dev(dev),
15 _channel(channel),
16 _baud(baud),
17 _flags(flags) {
18}
19
21
22 try {
23 this->disconnect();
24 }
25 catch(...) {
26 // Prevent propagation
27 }
28
29}
30
32
33 if (this->_handle >= 0) {
34 return;
35 }
36
37 const auto handle = ::lgSpiOpen(
38 this->_dev,
39 this->_channel,
40 this->_baud,
41 this->_flags);
42
43 if (handle < 0) {
44 throw std::runtime_error("failed to connect spi device");
45 }
46
47 this->_handle = handle;
48}
49
51 if (this->_handle < 0) {
52 return;
53 }
54
55 if (::lgSpiClose(this->_handle) != 0) {
56 throw std::runtime_error("failed to disconnect spi device");
57 }
58
59 this->_handle = -1;
60}
61
62unsigned short MCP3208::read(const std::uint8_t channel, const Mode m) const {
63
64 // Control bits for MCP3208 (12-bit ADC)
65 // First bit is single or differential mode
66 // Next three bits are channel selection (0 to 7)
67 // The last four bits are padding
68 const std::uint8_t ctrl =
69 (static_cast<std::uint8_t>(m) << 7) |
70 static_cast<std::uint8_t>((channel & 0b00000111) << 4)
71 ;
72
73 const std::uint8_t byteCount = 3;
74
75 // MCP3208 uses a 3-byte message (start bit + control + padding)
76 const std::uint8_t txData[byteCount] = {
77 0b00000110, // 3 leading zeros and start bit for MCP3208
78 ctrl, // sgl/diff (mode), d2, d1, d0, 4x "don't care" bits
79 0b00000000 // Padding bits (don't care)
80 };
81
82 std::uint8_t rxData[byteCount]{0};
83
84 const auto bytesTransferred = ::lgSpiXfer(
85 this->_handle,
86 reinterpret_cast<const char*>(txData),
87 reinterpret_cast<char*>(rxData), byteCount);
88
89 if (bytesTransferred != byteCount) {
90 throw std::runtime_error("SPI transfer failed");
91 }
92
93 // For MCP3208, the result is a 12-bit number:
94 // First 4 bits from the second byte and 8 bits from the third byte.
95 return
96 ((static_cast<unsigned short>(rxData[1]) & 0x0F) << 8) | // Top 4 bits from second byte
97 (static_cast<unsigned short>(rxData[2]) & 0xFF); // Bottom 8 bits from third byte
98}
99
100}; // End of namespace MCP3208Lib
MCP3208(const int dev=DEFAULT_SPI_DEV, const int channel=DEFAULT_SPI_CHANNEL, const int baud=DEFAULT_SPI_BAUD, const int flags=DEFAULT_SPI_FLAGS) noexcept
Definition MCP3208.cpp:8
unsigned short read(const std::uint8_t channel, const Mode m=Mode::SINGLE) const
Definition MCP3208.cpp:62
virtual ~MCP3208()
Definition MCP3208.cpp:20