Skip to content

Commit c528a21

Browse files
committed
I2C slave: allow function wrapped callbacks
Signed-off-by: hitech95 <nicveronese@gmail.com>
1 parent c6f3f08 commit c528a21

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

libraries/Wire/src/Wire.cpp

+26
Original file line numberDiff line numberDiff line change
@@ -437,6 +437,31 @@ void TwoWire::onRequestService(i2c_t *obj)
437437
}
438438
}
439439

440+
#ifdef __cplusplus
441+
// sets function called on slave write
442+
void TwoWire::onReceive(cb_function_receive_t function)
443+
{
444+
user_onReceive = function;
445+
}
446+
447+
void TwoWire::onReceive(void (*function)(int))
448+
{
449+
cb_function_receive_t _c = function;
450+
onReceive(_c);
451+
}
452+
453+
// sets function called on slave read
454+
void TwoWire::onRequest(cb_function_request_t function)
455+
{
456+
user_onRequest = function;
457+
}
458+
459+
void TwoWire::onRequest(void (*function)(void))
460+
{
461+
cb_function_request_t _c = function;
462+
onRequest(_c);
463+
}
464+
#else
440465
// sets function called on slave write
441466
void TwoWire::onReceive(void (*function)(int))
442467
{
@@ -448,6 +473,7 @@ void TwoWire::onRequest(void (*function)(void))
448473
{
449474
user_onRequest = function;
450475
}
476+
#endif
451477

452478
/**
453479
* @brief Allocate the Rx/Tx buffer to the requested length if needed

libraries/Wire/src/Wire.h

+17
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,10 @@ extern "C" {
2828
#include "utility/twi.h"
2929
}
3030

31+
#ifdef __cplusplus
32+
#include <functional>
33+
#endif
34+
3135
// Minimal buffer length. Buffers length will be increased when needed,
3236
// but TX buffer is limited to a maximum to avoid too much stack consumption
3337
// Note: Buffer length and max buffer length are limited by uin16_t type
@@ -56,8 +60,13 @@ class TwoWire : public Stream {
5660
uint8_t ownAddress;
5761
i2c_t _i2c;
5862

63+
#ifdef __cplusplus
64+
std::function<void(int)> user_onReceive;
65+
std::function<void(void)> user_onRequest;
66+
#else
5967
void (*user_onRequest)(void);
6068
void (*user_onReceive)(int);
69+
#endif
6170
static void onRequestService(i2c_t *);
6271
static void onReceiveService(i2c_t *);
6372

@@ -113,6 +122,14 @@ class TwoWire : public Stream {
113122
void onReceive(void (*)(int));
114123
void onRequest(void (*)(void));
115124

125+
#ifdef __cplusplus
126+
typedef std::function<void(int)> cb_function_receive_t;
127+
typedef std::function<void(void)> cb_function_request_t;
128+
129+
void onReceive(cb_function_receive_t callback);
130+
void onRequest(cb_function_request_t callback);
131+
#endif
132+
116133
inline size_t write(unsigned long n)
117134
{
118135
return write((uint8_t)n);

0 commit comments

Comments
 (0)