-
Notifications
You must be signed in to change notification settings - Fork 0
/
MCP3202.cpp
65 lines (52 loc) · 1.32 KB
/
MCP3202.cpp
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
/**
* @file MCP3202.cpp
* @author Davide Scalisi
* @brief
* @version 1.0
* @date 2022-03-26
*
* @copyright Copyright (c) 2022
*
*/
#include <MCP3202.h>
MCP3202::MCP3202(uint8_t CS, SPIClass mySPI){
this->CS = CS;
this->link = mySPI;
pinMode(CS, OUTPUT);
digitalWrite(CS, HIGH);
link.begin();
}
uint16_t MCP3202::read(uint8_t ch){
/*
MCU PIN:
Dout X X X X X X X A B C D X X X X X X X X X X X X X X
Din X X X X X X X X X X X X 0 B11 B10 B9 B8 B7 B6 B5 B4 B3 B2 B1 B0
A: Start bit.
B: 1: Single mode, 0: Differential mode.
C:
Single mode.:
0: Read from CH0.
1: Read from CH1.
Differential mode:
0: CH0: IN+, CH1: IN-.
1: CH0: IN-, CH1: IN+.
D: 1: MSB First, 0: LSB First (for the LSB, please refer to the datasheet).
*/
uint8_t msb, lsb, command = B10100000;
if(ch == 1)
command = B11100000;
/*
From the datasheet:
Supply voltage: 2.7V 5V
Max. clock freq.: 0.9MHz 1.8MHz
Let's use 1MHz, so that both at 5V and 3.3V there will be no communication errors.
*/
link.beginTransaction(SPISettings(2000000, MSBFIRST, SPI_MODE0));
digitalWrite(CS, LOW);
link.transfer(1); //Start bit.
msb = link.transfer(command) & 0x0F;
lsb = link.transfer(0);
digitalWrite(CS, HIGH);
link.endTransaction();
return ((int16_t) msb) << 8 | lsb;
}