Skip to content

Instantly share code, notes, and snippets.

@errkk
Created January 4, 2016 21:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save errkk/add880e12731ddb861ef to your computer and use it in GitHub Desktop.
Save errkk/add880e12731ddb861ef to your computer and use it in GitHub Desktop.
#include <TinyWireS.h>
// MAX INT 32767
#ifndef TWI_RX_BUFFER_SIZE
#define TWI_RX_BUFFER_SIZE (16)
#endif
#define ADDR 0x11
#define PIN 3
// Flow meter Variables
uint8_t flowState = 0;
uint8_t lastFlowState = 0;
unsigned long lastTick;
unsigned long timeBetweenTicks = 0;
const int litersPerTick = 10;
float litersPerSec = 0;
uint8_t litersPerMin = 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()
{
TinyWireS.send(byte(litersPerMin)); // its a uint8_t so it can go as one byte.
// Note this number can only be 0 - 255 (unsigned 8 bit), otherwise the payload has to be split into bytes and buffered in this function
// Increment the reg position on each read, and loop back to zero
}
void setup() {
TinyWireS.begin(ADDR);
TinyWireS.onRequest(requestEvent);
pinMode(PIN, INPUT);
}
void loop() {
flowState = digitalRead(PIN);
if (flowState != lastFlowState) {
if (flowState == LOW) {
unsigned long newTime = millis();
timeBetweenTicks = newTime - lastTick;
if(timeBetweenTicks > 1000) {
lastTick = newTime;
litersPerSec = litersPerTick / (timeBetweenTicks / 1000.0);
litersPerMin = int(litersPerSec * 60);
}
}
}
// save the current state as the last state,
// for next time through the loop
lastFlowState = flowState;
/**
* This is the only way we can detect stop condition (http://www.avrfreaks.net/index.php?name=PNphpBB2&file=viewtopic&p=984716&sid=82e9dc7299a8243b86cf7969dd41b5b5#984716)
* it needs to be called in a very tight loop in order not to miss any (REMINDER: Do *not* use delay() anywhere, use tws_delay() instead).
* It will call the function registered via TinyWireS.onReceive(); if there is data in the buffer on stop.
*/
TinyWireS_stop_check();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment