summaryrefslogtreecommitdiff
path: root/lib/Arduino_I2C_Port_Expander/src/Arduino_I2C_Port_Expander.cpp
blob: 70470e99977658aff049423f24b9e0d799abddc9 (plain)
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
#include "Arduino_I2C_Port_Expander.h" //include the declaration for this class

byte io_DataPacket[3];
byte io_pin;
byte io_method;
byte io_value;
uint8_t _addr;
  
//<<constructor>>
EXPAND::EXPAND(uint8_t addr){
  _addr = addr;
}

//<<destructor>>
EXPAND::~EXPAND(){/*nothing to destruct*/}

void EXPAND::digitalWrite(byte pin,byte val){
  io_DataPacket[0] = 1;    // method
  io_DataPacket[1] = pin;  // pin
  io_DataPacket[2] = val;  // val
  sendDataPacket();
  int received = receiveResponse();
}

int EXPAND::digitalRead(byte pin){
  io_DataPacket[0] = 2;    // method
  io_DataPacket[1] = pin;  // pin
  sendDataPacket();
  int received = receiveResponse();
  return received;
}

int EXPAND::digitalReadPullup(byte pin){
  io_DataPacket[0] = 3;    // method
  io_DataPacket[1] = pin;  // pin
  sendDataPacket();
  int received = receiveResponse();
  return received;
}

void EXPAND::analogWrite(byte pin,byte val){
  io_DataPacket[0] = 4;    // method
  io_DataPacket[1] = pin;  // pin
  io_DataPacket[2] = val;  // val
  sendDataPacket();
  int received = receiveResponse();
}

int EXPAND::analogRead(byte pin){
  io_DataPacket[0] = 5;    // method
  io_DataPacket[1] = pin;  // pin
  sendDataPacket();
  int received = receiveResponse();
  return received;
}

void EXPAND::analogWriteSlow(byte pin,byte val){
  io_DataPacket[0] = 10;   // method
  io_DataPacket[1] = pin;  // pin
  io_DataPacket[2] = val;  // val
  sendDataPacket();
  int received = receiveResponse();
}


void EXPAND::sendDataPacket(){
  Wire.beginTransmission(_addr);
  Wire.write(io_DataPacket, 3);
  Wire.endTransmission(true);
  delay(1);
}

int EXPAND::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;  
}