-
Notifications
You must be signed in to change notification settings - Fork 0
/
Ultimate_Port_Expander.cpp
80 lines (70 loc) · 1.85 KB
/
Ultimate_Port_Expander.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
#include "Ultimate_Port_Expander.h"
//<<constructor>>
UPE::UPE(uint8_t addr){
_addr = addr;
//Wire.begin();
}
//<<destructor>>
UPE::~UPE(){/*nothing to destruct*/}
void UPE::digitalWrite(byte pin,byte val){
uint8_t dataPacket[3];
dataPacket[0] = DIGITAL_WRITE; // method
dataPacket[1] = pin; // pin
dataPacket[2] = val; // val
sendDataPacket(dataPacket,3);
int received = receiveResponse();
}
int UPE::digitalRead(byte pin){
uint8_t dataPacket[2];
dataPacket[0] = DIGITAL_READ; // method
dataPacket[1] = pin; // pin
sendDataPacket(dataPacket,2);
int received = receiveResponse();
return received;
}
int UPE::digitalReadPullup(byte pin){
uint8_t dataPacket[2];
dataPacket[0] = DIGITAL_READ_PULLUP; // method
dataPacket[1] = pin; // pin
sendDataPacket(dataPacket,2);
int received = receiveResponse();
return received;
}
void UPE::analogWrite(byte pin,byte val){
uint8_t dataPacket[3];
dataPacket[0] = ANALOG_WRITE; // method
dataPacket[1] = pin; // pin
dataPacket[2] = val; // val
sendDataPacket(dataPacket,3);
int received = receiveResponse();
}
int UPE::analogRead(byte pin){
uint8_t dataPacket[2];
dataPacket[0] = ANALOG_READ; // method
dataPacket[1] = pin; // pin
sendDataPacket(dataPacket, 2);
int received = receiveResponse();
return received;
}
void UPE::sendDataPacket(uint8_t dataPacket[], uint8_t size){
Wire.beginTransmission(_addr);
Wire.write(dataPacket, size);
Wire.endTransmission(true);
// delay(1);
}
int UPE::receiveResponse(){
unsigned int receivedValue;
int available = Wire.requestFrom(_addr, (byte)1);
byte buffer[2];
if(available == 1)
{
buffer[0] = Wire.read();
}
available = Wire.requestFrom(_addr, (byte)1);
if(available == 1)
{
buffer[1] = Wire.read();
}
receivedValue = buffer[0] << 8 | buffer[1];
return receivedValue;
}