lichtorgel/lichtorgel.ino

136 lines
2.9 KiB
C++

//echo -n "110010" >/dev/udp/192.168.178.25/4210
//Node MCU 1.0 ESP-12E
//1M SPIFFS
//80MHz
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include "wificredentials.h"
/* content:
* const char* ssid = "SSIDHERE";
* const char* password = "password";
*/
WiFiUDP Udp;
unsigned int localUdpPort = 4210; // local port to listen on
char incomingPacket[255]; // buffer for incoming packets
bool wlan=true;
#define PIN_SR_DATA D5
#define PIN_SR_LTCH D6
#define PIN_SR_CLOCK D7
#define OUTPUTS 6
long lastTickMillis;
uint8_t out[OUTPUTS];
long lastChange=0;
#define STANDBYTIME 5000 //time in ms after lamps switch off if nothing happened
boolean standby=false;
void setup()
{
pinMode(PIN_SR_DATA, OUTPUT);
pinMode(PIN_SR_LTCH, OUTPUT);
pinMode(PIN_SR_CLOCK, OUTPUT);
shiftRelais(0);
Serial.begin(115200);
Serial.println();
Serial.printf("Connecting to %s ", ssid);
WiFi.begin(ssid, password);
uint8_t wlantries=20;
while ((WiFi.status() != WL_CONNECTED) && wlan)
{
delay(500);
Serial.print(".");
if (wlantries<=0){
wlan=false; //deactivate wlan
}
wlantries--;
}
if(wlan){
Serial.println(" connected");
Udp.begin(localUdpPort);
Serial.printf("Now listening at IP %s, UDP port %d\n", WiFi.localIP().toString().c_str(), localUdpPort);
}else{
Serial.println("wlan not connected");
}
}
void loop()
{
int packetSize = Udp.parsePacket();
if (packetSize)
{
// receive incoming UDP packets
Serial.printf("Received %d bytes from %s, port %d\n", packetSize, Udp.remoteIP().toString().c_str(), Udp.remotePort());
int len = Udp.read(incomingPacket, 255);
if (len > 0)
{
incomingPacket[len] = 0;
}
uint16_t data=incomingPacket[0]<<8 | incomingPacket[1];
Serial.printf("UDP packet contents: %s\n", incomingPacket);
printBinary(data);
printBinary(mapData(data));
shiftRelais(mapData(data));
lastChange=millis();
standby=false;
}
if (millis()-lastChange >=STANDBYTIME && !standby){
Serial.println("Standby");
shiftRelais(mapData(0));
standby=true;
}
}
void printBinary(uint16_t value){
for(int i = 15; i >=0; i--) {
Serial.print((value & (1 << ((byte)i) )) ? 1 : 0);
//Serial.print(!!(value & (1 << i))); //this should also work
}
Serial.println();
}
uint16_t mapData(uint16_t x){
uint16_t d=0;
d|=moveByte(x,0,1);
d|=moveByte(x,1,2);
d|=moveByte(x,2,3);
d|=moveByte(x,3,4);
d|=moveByte(x,4,5);
d|=moveByte(x,5,6);
d|=moveByte(x,6,7);
d|=moveByte(x,7,0);
return d;
}
uint16_t moveByte(uint16_t x,uint8_t from,uint8_t to){
//example: x=00110101 from=2 to=0 -> 00000001
return ((x&_BV(from))>0) ? _BV(to):0;
}
void shiftRelais(uint16_t data) {
digitalWrite(PIN_SR_LTCH, LOW);
shiftOut(PIN_SR_DATA, PIN_SR_CLOCK, MSBFIRST, (data >> 8));
shiftOut(PIN_SR_DATA, PIN_SR_CLOCK, MSBFIRST, data & 0xff);
digitalWrite(PIN_SR_LTCH, HIGH);
}