Advertisement
babyyoda_

WorkingAttinySlave

Jul 2nd, 2021
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <TimerOne.h>
  2.  
  3. #include "PinChangeInterrupt.h"
  4. #include "TinyWireS.h"
  5.  
  6. #define I2C_SLAVE_ADDR  2
  7. int AC_LOAD = 3;
  8. int ZCD_Pin = 1;
  9. int dimming = 128;
  10. int Speed[3] = {90, 50, 20};
  11. int speedValue;
  12. bool fan;
  13. bool interruptState;
  14.  
  15. void setup() {
  16.   pinMode(AC_LOAD, OUTPUT);
  17.   TinyWireS.begin(I2C_SLAVE_ADDR);
  18.   TinyWireS.onReceive(receiveEvent);
  19.   pinMode(ZCD_Pin, INPUT_PULLUP);
  20.  
  21. }
  22.  
  23.  
  24. void zero_crosss_int()  //function to be fired at the zero crossing to dim the light
  25. {
  26.   interruptState = true;
  27.  
  28. }
  29.  
  30. void blinkLed() {
  31.  
  32.   Timer1.stop();
  33.   //  delayMicroseconds(dimtime);    // Wait till firing the TRIAC
  34.   digitalWrite(AC_LOAD, HIGH);   // Fire the TRIAC
  35.   delayMicroseconds(100);         // triac On propogation delay  // (for 60Hz use 8.33) Some Triacs need a longer period
  36.   digitalWrite(AC_LOAD, LOW);    // No longer trigger the TRIAC (the next zero crossing will swith it off) TRIAC
  37. }
  38.  
  39. void receiveEvent(uint8_t howMany)
  40. {
  41.   byte byteRcvd = 0;
  42.   if (TinyWireS.available()) {
  43.     byteRcvd = TinyWireS.receive();     // get the byte from master
  44.  
  45.     if (byteRcvd == '0') {
  46.       fan = false;
  47.       detachPinChangeInterrupt(digitalPinToPCINT(ZCD_Pin));
  48.       digitalWrite(AC_LOAD, LOW);
  49.     }
  50.     if (byteRcvd == '1') {
  51.       fan = true;
  52.       speedValue = Speed[0];    //90
  53.       attachPCINT(digitalPinToPCINT(ZCD_Pin), zero_crosss_int, RISING);
  54.     }
  55.     if (byteRcvd == '2') {
  56.       fan = true;
  57.       speedValue = Speed[1];   //50
  58.       attachPCINT(digitalPinToPCINT(ZCD_Pin), zero_crosss_int, RISING);
  59.     }
  60.     if (byteRcvd == '3') {
  61.       fan = true;
  62.       speedValue = Speed[2];  //20
  63.       attachPCINT(digitalPinToPCINT(ZCD_Pin), zero_crosss_int, RISING);
  64.     }
  65.     dimming = speedValue;
  66.   }
  67. }
  68.  
  69. void loop() {
  70.   if (interruptState = true) {
  71.     long int dimtime;
  72.     dimtime = (75 * dimming);  // For 60Hz =>65
  73.     if (fan) {
  74.       Timer1.initialize(dimtime);
  75.       Timer1.attachInterrupt(blinkLed);
  76.       Timer1.start();
  77.     }
  78.   }
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement