#include <Wire.h>
int ledPin = 13;//on TeensyLC
int mindex = 0;
int packetsRxed = 0;
unsigned long lastPacketRxedTime = 0L;
unsigned long now = 0L;
int buffer[32];
boolean dataAvailable = false;
//Define hardware serial port #1 on the TeensyLC as btModule
#define btModule Serial1
//////////////UTILITY/////////////////////////
boolean ledOn(){
return digitalRead(ledPin);
}
void toggleLED(){
digitalWrite(ledPin,!ledOn());
}
//////////////SETUP/////////////////////////
void setup()
{
//Serial.begin(19200); // start serial for output
btModule.begin(19200);
pinMode(ledPin, OUTPUT);
digitalWrite(ledPin,HIGH); //start LED as ON.
//Blink the LED 2 times and leave on...
//The LED starts as ON, so you get ON, OFF, ON, OFF, steady ON
for (int i=0; i <2 ; i++){
delay(250);
toggleLED(); //off
delay(250);
toggleLED(); //on
}
//Serial.println("Starting");
Wire.begin(0x00); // get general call
Wire.onReceive(receiveEvent); // register event
lastPacketRxedTime = millis();//initialize the led toggle timer
}
//////////////LOOP/////////////////////////
void loop()
{
delay(5);
now = millis();
//Blinking LED means data is being received, steady ON means no data
//has been received for awhile.
//
//Toggle the LED after 10 packets have been received OR
//more than 1 second has gone by and there is a new packet received. This keeps
//the LED blinking even if the data is coming in slowly...
if ((packetsRxed > 10) || (dataAvailable & ((now - lastPacketRxedTime) > 1000L))){
toggleLED();
packetsRxed = 0;
}
//if it has been 3 seconds since the last packet was received and there is
//not new data coming in and the LED is off,
//turn the led back on to show we are still alive
if (((now - lastPacketRxedTime) > 3000L) && !ledOn() && !dataAvailable){
toggleLED();
}
if (dataAvailable) {
dataAvailable = false;
//Serial.print(mindex);
//Serial.print(":");
//write it to the Bluetooth SPP (and Serial port for debugging)...
for (int i=0; i<mindex; i++){
btModule.write(buffer[i]);
//Serial.print(buffer[i],HEX);
//Serial.print(':');
}
//Serial.println("[EOM]");
}
}
//////////////EVENT/////////////////////////
// function that executes whenever data is received from master
// this function is registered as an event, see setup()
// Get the data and get out of this routine. Set a flag to
// transmit the data on the main loop.
//
void receiveEvent(int howMany){
if (howMany < 1) // Sanity-check
return;
if (howMany > 32) // Also insane number
return;
packetsRxed++;
int i = 0;
while(Wire.available())
buffer[i++] = Wire.read(); // receive bytes
//leave mindex alone for as long as possible...
mindex = i;
dataAvailable = true;
}