Skip to content

Instantly share code, notes, and snippets.

@normen
Created June 15, 2017 12:30
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 normen/615fadaedb917b68f78a91ac84365056 to your computer and use it in GitHub Desktop.
Save normen/615fadaedb917b68f78a91ac84365056 to your computer and use it in GitHub Desktop.
homebridge-433-arduino code
/*
Arduino code for homebridge-433-arduino
(c) by Normen Hansen, released under MIT license
uses code from http://forum.arduino.cc/index.php?topic=396450.0
*/
#include <RCSwitch.h>
RCSwitch mySwitch = RCSwitch();
const byte numChars = 255; // max number of received chars
char receivedChars[numChars]; // an array to store the received data
boolean newData = false; // was a full new string received?
String dash = "/";
void setup() {
Serial.begin(9600);
Serial.setTimeout(100);
mySwitch.enableReceive(0); // Receiver on interrupt 0 => that is pin #3 on micro!!
mySwitch.enableTransmit(4); // Actual Pin 4
mySwitch.setRepeatTransmit(5);
}
// gets the values from a string formatted like 123456/123
String getValue(String data, char separator, int index) {
int found = 0;
int strIndex[] = {0, -1};
int maxIndex = data.length()-1;
for(int i=0; i<=maxIndex && found<=index; i++){
if(data.charAt(i)==separator || i==maxIndex){
found++;
strIndex[0] = strIndex[1]+1;
strIndex[1] = (i == maxIndex) ? i+1 : i;
}
}
return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
}
void receiveSerialData() {
static byte ndx = 0;
char endMarker = '\n';
char rc;
if (Serial.available() > 0) {
rc = Serial.read();
if (rc != endMarker) {
receivedChars[ndx] = rc;
ndx++;
if (ndx >= numChars) {
ndx = numChars - 1;
}
}
else {
receivedChars[ndx] = '\0'; // terminate the string
ndx = 0;
newData = true;
}
}
}
void sendRcData() {
if (newData == true) {
long value = getValue(receivedChars, '/', 0).toInt();
long pulse = getValue(receivedChars, '/', 1).toInt();
mySwitch.setPulseLength(pulse);
mySwitch.send(value, 24);
Serial.println("OK");
newData = false;
}
}
void receiveRcData(){
if (mySwitch.available()) {
long value = mySwitch.getReceivedValue();
long pulse = mySwitch.getReceivedDelay();
if (value != 0) {
String out = value + dash + pulse;
Serial.println( out );
}
mySwitch.resetAvailable();
}
}
void loop() {
receiveSerialData();
sendRcData();
receiveRcData();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment