Created
June 2, 2015 05:57
-
-
Save monpetit/4a851f169090167c7d97 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define I2C_SLAVE_ADDRESS 0x4 // the 7-bit address | |
// Get this from https://github.com/rambo/TinyWire | |
#include <TinyWireS.h> | |
// The default buffer size, though we cannot actually affect it by defining it in the sketch | |
#ifndef TWI_RX_BUFFER_SIZE | |
#define TWI_RX_BUFFER_SIZE (16) | |
#endif | |
#define MEASURE_TEMPERATURE 0xA0 | |
#define SEND_TEMPERATURE 0xB0 | |
int sensorPin = A3; // select the input pin for the ADC | |
static int temperature = 0; | |
static uint8_t tempbuf[2] = {0}; | |
volatile int buffer_index = 0; | |
volatile uint8_t i2c_cmd; | |
volatile bool send_flag = false; | |
void measure_temperature(void); | |
void receiveEvent(uint8_t howMany); | |
void requestEvent(void); | |
void setup(void) | |
{ | |
analogReference(DEFAULT); | |
measure_temperature(); | |
TinyWireS.begin(I2C_SLAVE_ADDRESS); | |
TinyWireS.onReceive(receiveEvent); | |
TinyWireS.onRequest(requestEvent); | |
} | |
void loop(void) | |
{ | |
TinyWireS_stop_check(); | |
} | |
void measure_temperature(void) | |
{ | |
temperature = analogRead(sensorPin); | |
tempbuf[0] = (uint8_t) (temperature >> 8); | |
tempbuf[1] = (uint8_t) (temperature & 0xff); | |
} | |
/** | |
* The I2C data received -handler | |
* | |
* This needs to complete before the next incoming transaction (start, data, restart/stop) on the bus does | |
* so be quick, set flags for long running tasks to be called from the mainloop instead of running them directly, | |
*/ | |
void receiveEvent(uint8_t howMany) | |
{ | |
if (howMany < 1) { | |
// Sanity-check | |
return; | |
} | |
if (howMany > TWI_RX_BUFFER_SIZE) { | |
// Also insane number | |
return; | |
} | |
i2c_cmd = TinyWireS.receive(); | |
howMany--; | |
if (i2c_cmd == MEASURE_TEMPERATURE) { | |
measure_temperature(); | |
} | |
if (i2c_cmd == SEND_TEMPERATURE) { | |
send_flag = true; | |
buffer_index = 0; | |
} | |
} | |
/** | |
* This is called for each read request we receive, never put more than one byte of data (with TinyWireS.send) to the | |
* send-buffer when using this callback | |
*/ | |
void requestEvent(void) | |
{ | |
if (send_flag) { | |
TinyWireS.send(tempbuf[buffer_index]); | |
buffer_index++; | |
if (buffer_index > 1) { | |
send_flag = false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment