Last active
December 10, 2015 12:48
-
-
Save roberttwomey/4436501 to your computer and use it in GitHub Desktop.
electric imp code for ac dimming circuit
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
// Electric Imp code example - AC dimmer | |
// Define zero crossing period = 1 / Mains Freq / 2 | |
// 60Hz = 0.008333, 50Hz = 0.01 | |
const ZEROT = 0.008333; | |
local pinZerox = hardware.pin9; // Pin to use as zero cross input | |
local pinTriac = hardware.pin2; // Pin to use for triac control | |
local level = 0.5; // Dimmer level 0.0 = Off, 1.0 = Full bright | |
local tic=0; | |
local toc=0; | |
// Derive our input class from InputPort | |
class input extends InputPort | |
{ | |
function set(newLevel) | |
{ | |
// Validate and store the new level | |
if(newLevel < 0.0) newLevel = 0.0; | |
if(newLevel > 1.0) newLevel = 1.0; | |
level = newLevel; | |
// Display level on the Planner node | |
server.show(format("%3.1f%%", level * 100.0)); | |
} | |
} | |
// Zero crossing event handler, called every time the AC output crosses 0V | |
function zeroxEvent() | |
{ | |
// ignore falling edge | |
if(pinZerox.read() == 0) return; | |
// ignore rising edge | |
//if(pinZerox.read() > 0) return; | |
tic = tic +1; | |
if(tic>120) { | |
tic=0; | |
toc=toc+1; | |
server.show(format("%d secs %3.1f%%", toc, level * 100.0)); | |
} | |
// Leave triac off for levels < 0.05 | |
//if(level < 0.05) | |
//{ | |
// pinTriac.write(1); | |
// return; | |
//} | |
// "chop off": turn off the triac | |
pinTriac.write(0); | |
// Leave triac on for levels > 0.95 | |
if(level < 0.25) return; | |
// Otherwise sleep for part of the AC cycle | |
imp.sleep(ZEROT * (1.0-level)); | |
//imp.wakeup(ZEROT * (1.0-level), chopOn); | |
// "chop on": turn the triac on and leave on until next zero cross | |
pinTriac.write(1); | |
} | |
function chopOn() { | |
pinTriac.write(1); | |
} | |
//function watchdog() { | |
//imp.wakeup(60,watchdog); | |
//server.log("watchdog"); | |
//} | |
// | |
//// start watchdog write every 60 seconds | |
//watchdog(); | |
// Configure pin functions | |
pinTriac.configure(DIGITAL_OUT); | |
pinZerox.configure(DIGITAL_IN, zeroxEvent); | |
// Register with the server | |
imp.configure("AC Dimmer", [input("Level", "number")], []); | |
// Initialise the node display | |
//server.show("0%"); | |
server.show(format("%3.1f%%", level * 100.0)); | |
// End of code. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment