forked from whatnick/ADE7816_Arduino
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ADE7816_SPI.cpp
98 lines (91 loc) · 2.42 KB
/
ADE7816_SPI.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
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
/*************************************************************************************/
/* Base implementation around .js prior art here */
/* https://github.com/tadakado/smart-meter/blob/master/Soft/OLD_spi/02_initialize.js */
/*************************************************************************************/
#include "ADE7816.h"
#include "SPI.h"
SPIClass spi;
ADE7816_SPI::ADE7816_SPI()
{
spi = SPIClass();
settings();
}
void ADE7816_SPI::begin(int8_t sck, int8_t miso, int8_t mosi, int8_t ss)
{
#ifdef ARDUINO_ARCH_ESP32
spi.begin(sck, miso, mosi, ss);
#else
spi.begin();
#endif
_ss = ss;
pinMode(_ss, OUTPUT);
digitalWrite(_ss, HIGH);
delay(1);
for (int i = 0; i < 4; i++)
{
digitalWrite(_ss, LOW);
delayMicroseconds(10);
digitalWrite(_ss, HIGH);
delayMicroseconds(10);
}
}
void ADE7816_SPI::settings(uint32_t clock, uint8_t bitOrder, uint8_t dataMode)
{
_clock = clock;
_bitOrder = bitOrder;
_dataMode = dataMode;
}
void ADE7816_SPI::writeRegister(uint16_t reg, uint16_t val)
{
uint8_t fba = 0x0;
uint8_t hba = reg >> 8;
uint8_t lba = reg & 0xff;
uint8_t hbv = val >> 8;
uint8_t lbv = val & 0xff;
digitalWrite(_ss, LOW);
spi.beginTransaction(SPISettings(_clock, _bitOrder, _dataMode));
spi.transfer(fba);
spi.transfer(hba);
spi.transfer(lba);
spi.transfer(hbv);
spi.transfer(lbv);
spi.endTransaction();
digitalWrite(_ss, HIGH);
}
uint32_t ADE7816_SPI::readRegister(uint16_t reg)
{
uint8_t fba = 0x1;
uint8_t hba = reg >> 8;
uint8_t lba = reg & 0xff;
uint32_t res = 0;
digitalWrite(_ss, LOW);
spi.beginTransaction(SPISettings(_clock, _bitOrder, _dataMode));
spi.transfer(fba);
spi.transfer(hba);
spi.transfer(lba);
uint8_t rb0 = spi.transfer(0x0);
uint8_t rb1 = spi.transfer(0x0);
uint8_t rb2 = spi.transfer(0x0);
uint8_t rb3 = spi.transfer(0x0);
res |= rb0;
res = (res << 8) | rb1;
res = (res << 8) | rb2;
res = (res << 8) | rb3;
spi.endTransaction();
digitalWrite(_ss, HIGH);
return res;
}
void ADE7816_SPI::runDsp()
{
ADE7816_SPI::writeRegister(Run, 1);
}
void ADE7816_SPI::stopDsp()
{
writeRegister(Run, 0);
}
int ADE7816_SPI::_writeRegister(const unsigned int reg, const unsigned int val){
return 0;
}
int ADE7816_SPI::_readRegister(const unsigned int reg){
return 0;
}