Skip to content

Instantly share code, notes, and snippets.

@elecnix
Created June 16, 2016 00:04
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 elecnix/74d74cf02b2bb80158bc6952dde740d4 to your computer and use it in GitHub Desktop.
Save elecnix/74d74cf02b2bb80158bc6952dde740d4 to your computer and use it in GitHub Desktop.
#include "SparkIntervalTimer/SparkIntervalTimer.h"
//SYSTEM_MODE (MANUAL);
volatile int i = 0; // Variable to use as a counter volatile as it is in an interrupt
volatile boolean zero_cross = 0; // Boolean to store a "switch" to tell us if we have crossed zero
int AC_pin = D7; // Output to Opto Triac
int dim = 0; // Dimming level (0-128) 0 = on, 128 = 0ff
int inc = 1; // counting up or down, 1=up, -1=down
int freqStep = 65; // This is the delay-per-brightness step in microseconds.
// For 60 Hz it should be 65
// It is calculated based on the frequency of your voltage supply (50Hz or 60Hz)
// and the number of brightness steps you want.
void zero_cross_detect();
int PIN_ZERO_CROSS = D2;
volatile int zeroCross = 0;
IntervalTimer timer;
void setup()
{
Serial.begin(9600);
pinMode(PIN_ZERO_CROSS, INPUT);
pinMode(AC_pin, OUTPUT); // Set the Triac pin as output
timer.begin(dim_check, freqStep, uSec, TIMER5);
attachInterrupt(PIN_ZERO_CROSS, zero_cross_detect, RISING, 0); // Attach an Interupt to Pin 2 (interupt 0) for Zero Cross Detection
}
void zero_cross_detect() {
zero_cross = true; // set the boolean to true to tell our dimming function that a zero cross has occured
i=0;
digitalWrite(AC_pin, LOW); // turn off TRIAC (and AC)
}
// Turn on the TRIAC at the appropriate time
void dim_check() {
//Serial.println("DIM CHECK");
if(zero_cross == true) {
if(i>=dim) {
digitalWriteFast(AC_pin, HIGH); // turn on light
i=0; // reset time step counter
zero_cross = false; //reset zero cross detection
}
else {
i++; // increment time step counter
}
}
}
void loop() {
dim+=inc;
if((dim>=128) || (dim<=0))
inc*=-1;
delay(10);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment