Skip to content

Commit 927685c

Browse files
committedApr 1, 2020
Wire: implement slave functionalities
1 parent 3b156f0 commit 927685c

File tree

2 files changed

+48
-3
lines changed

2 files changed

+48
-3
lines changed
 

‎libraries/Wire/Wire.cpp

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,8 @@ void arduino::MbedI2C::begin() {
3131
void arduino::MbedI2C::begin(uint8_t slaveAddr) {
3232
#ifdef DEVICE_I2CSLAVE
3333
slave = new mbed::I2CSlave((PinName)_sda, (PinName)_scl);
34-
slave->address(slaveAddr);
34+
slave->address(slaveAddr << 1);
35+
slave_th.start(mbed::callback(this, &arduino::MbedI2C::receiveThd));
3536
#endif
3637
}
3738

@@ -118,9 +119,45 @@ int arduino::MbedI2C::peek() {
118119
void arduino::MbedI2C::flush() {
119120
}
120121

122+
void arduino::MbedI2C::receiveThd() {
123+
while (1) {
124+
int i = slave->receive();
125+
switch (i) {
126+
case mbed::I2CSlave::ReadAddressed:
127+
if (onRequestCb != NULL) {
128+
onRequestCb();
129+
}
130+
slave->write((const char *) txBuffer, usedTxBuffer);
131+
slave->stop();
132+
break;
133+
case mbed::I2CSlave::WriteGeneral:
134+
case mbed::I2CSlave::WriteAddressed:
135+
rxBuffer.clear();
136+
char buf[16];
137+
while (1) {
138+
int c = slave->read(buf, sizeof(buf));
139+
for (int i = 0; i < c; i++) {
140+
rxBuffer.store_char(uint8_t(buf[i]));
141+
}
142+
if (c <= sizeof(buf)) {
143+
break;
144+
}
145+
}
146+
if (rxBuffer.available() > 0 && onReceiveCb != NULL) {
147+
onReceiveCb(rxBuffer.available());
148+
}
149+
slave->stop();
150+
break;
151+
}
152+
}
153+
}
121154

122-
void arduino::MbedI2C::onReceive(void(*)(int)) {}
123-
void arduino::MbedI2C::onRequest(void(*)(void)) {}
155+
void arduino::MbedI2C::onReceive(voidFuncPtrParamInt cb) {
156+
onReceiveCb = cb;
157+
}
158+
void arduino::MbedI2C::onRequest(voidFuncPtr cb) {
159+
onRequestCb = cb;
160+
}
124161

125162

126163
#if WIRE_HOWMANY > 0

‎libraries/Wire/Wire.h

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,12 @@
1919
#pragma once
2020

2121
#include "Arduino.h"
22+
#include "Print.h"
2223
#include "drivers/I2C.h"
2324
#include "drivers/I2CSlave.h"
2425

26+
typedef void (*voidFuncPtrParamInt)(int);
27+
2528
namespace arduino {
2629

2730
class MbedI2C : public HardwareI2C
@@ -46,6 +49,7 @@ class MbedI2C : public HardwareI2C
4649

4750
virtual size_t write(uint8_t data);
4851
virtual size_t write(const uint8_t* data, int len);
52+
using Print::write;
4953
virtual int read();
5054
virtual int peek();
5155
virtual void flush();
@@ -63,6 +67,10 @@ class MbedI2C : public HardwareI2C
6367
RingBufferN<256> rxBuffer;
6468
uint8_t txBuffer[256];
6569
uint32_t usedTxBuffer;
70+
voidFuncPtrParamInt onReceiveCb = NULL;
71+
voidFuncPtr onRequestCb = NULL;
72+
rtos::Thread slave_th;
73+
void receiveThd();
6674
};
6775

6876
}

0 commit comments

Comments
 (0)
Please sign in to comment.