├── LICENSE ├── README.md ├── examples └── basic_example │ ├── basic_example.ino │ └── potentiometer.ino ├── fritzing.fzz ├── fritzing.png ├── keywords.txt ├── library.properties └── src ├── TriacDimmer.cpp └── TriacDimmer.h /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TriacDimmer 2 | The _high-performance_ arduino triac dimming library. 3 | 4 | This library was designed to perform phase-control dimming control on a triac dimming circuit, 5 | leveraging the ATmega328p's built-in timer peripheral to perform all time-critical functionality directly in hardware, 6 | without the need to spend CPU time on an expensive control loop. 7 | 8 | Note that this library is intended to control mains AC power. 9 | Make sure you understand the risks and take appropriate precautions before working with mains AC. 10 | 11 | The phase offsets are calculated based on the _measured_ mains frequency, 12 | so this code will work regardless of 50/60Hz or any other frequency. 13 | This includes correcting for any inaccuracies in the arduino's oscillator or the mains frequency. 14 | 15 | This library was developed specifically for the Krida 2 CH Dimmer 16 | ([amazon](https://www.amazon.com/Dimmer-Module-Controller-Arduino-Raspberry/dp/B06Y1GVG26), 17 | [alibaba](https://mdwdz.en.alibaba.com/product/60670737878-804998378/2CH_AC_LED_Light_Dimmer_Module_Controller_Board.html), 18 | [inmojo](http://www.inmojo.com/store/krida-electronics/item/2-channel-ac-led-bulb-dimmer-module-v2/)), 19 | and has been tested to work with the RobotDyn AC Dimmer 20 | ([robotdyn](https://robotdyn.com/ac-light-dimmer-module-1-channel-3-3v-5v-logic-ac-50-60hz-220v-110v.html)), 21 | and should work fine with other phase-control dimming circuits that output a positive edge on their sync signal. 22 | 23 | See [the example](examples/basic_example/basic_example.ino) for an example of how to use the library. 24 | The library methods themselves are documented in [the library header](src/TriacDimmer.h). 25 | 26 | This library **requires** the use of certain pins. 27 | Pin 8 _must_ be used as the sync input, and pins 9 and 10 are the only pins that can be used as channel outputs. 28 | This library _will not work_ on any other pins, period. 29 | 30 | ![fritzing diagram](fritzing.png) 31 | 32 | ## Flickering, and How to Fix It 33 | 34 | If you experience issues with flickering, here are a few things you might want to consider/try: 35 | 36 | ### Frequency Drift Calibration 37 | 38 | This library automatically recalibrates against frequency drift every time `setBrightness` is called, and the design decision to have the library do it this way has implications for how the library needs to be used. (A better design might make this 100% automatic in the future, though.) 39 | 40 | In order for the frequency drift calibration to work as expected, the library needs to observe a full waveform period between the initial `begin` and a `setBrightness` call. Without this, the library will assume a default calibration, but this default calibration is not going to be accurate, and is entirely wrong for any situation other than a 16MHz arduino controlling 60Hz power. 41 | 42 | Ensuring you have a valid drift calibration _could_ mean something as simplistic as sleeping for 20ms between `TriacDimmer::begin` and `TriacDimmer::setBrightness`, but in practice it's easier to just have one of your main loop tasks be calling `setBrightness` -- that way it will continuously compensate for temperature changes too. 43 | 44 | ### Signal Noise 45 | 46 | When working with power electronics, it always pays to be paranoid about signal noise. 47 | 48 | This library automatically enables the integrated noise-filtering function of the hardware it uses to help reduce the impact of noise on the sync input -- but this can only do so much. 49 | 50 | More filtering can be added by wiring a small capacitor (e.g. 1nF) between the sync signal and ground, close to the arduino board; or an even more advanced low-pass RC filter for those willing to do the math. 51 | 52 | In addition, you should also look at ways to reduce the nose at its source instead of just filtering it out after the fact. 53 | 54 | You may not need to be quite as paranoid as doing everything described here -- in fact, you most definitely should not do the last item -- but if it's not working yet... 55 | 56 | - Keep low voltage and high voltage wires as separate as you can manage, and make sure they are not parallel with each other. 57 | - Minimize loop area. Run the neutral wire for the circut backwards along the exact same path and as close as your insulation clearances allow to the hot wire, so that any magnetic fields from current in one wire are cancelled out by the return current in the other. 58 | - Add shielding. If low voltage and high voltage ever do need to be close or parallel, ensure at least one of the two is covered as much as you can manage with some sort of grounded metal -- whether that's a metal box around one of the two sections, a bot of copper foil tape wrapped around a bundle of wires, or whatever else you need. 59 | - Realize that single-ended signals are a lie we tell beginners and car mechanics -- everything is differential, _how_ differential jut depends on frequency. Run a twisted pair for each signal and use the other conductor in each pair as a dedicated signal return connected to the closest ground at each end. 60 | - Abandon all hope and confront your imposter syndrome by adding "real" differential transcievers. 61 | 62 | ### Tune the Pulse Generation Parameters 63 | 64 | There are a handful of parameters you can pass to `begin` that can be adjusted depending on what sort of flickering you have. 65 | By default, with no arguments the library uses these values as defaults: 66 | 67 | ```cpp 68 | TriacDimmer::begin(pulse_length = 20, min_trigger = 2000, on_thresh = 2, off_thresh = 0.01) 69 | ``` 70 | 71 | First off, if you experience flickering regardless of the brightness value you set, increase `pulse_length` from the default `20` to a larger value like `50` or `100` until `TriacDimmer::setBrightness(pin, 0.5);` results in a stable glow. 72 | 73 | Once it's stable at 0.5, set the brightness 1.0 (`TriacDimmer::setBrightness(pin, 1.0);`) and check for flickering. 74 | There shouldn't be any, but if there is you can increase `min_trigger` from the default `2000` to perhaps `3000` or `4000` until the flickering stops. 75 | If you're still experiencing flickering no matter how large `min_trigger` is, you can also try setting `on_thresh` to below the highest brightness level that causes flickering. This shouldn't normally be necessary though, as adjusting `min_trigger` should normally be enough. 76 | 77 | The last step is to figure out the lowest brightness value can sustain without flickering. 78 | By default the library is set to cut off completely for brightness values smaller than `0.01`, but if you still see flickering at `0.015` or `0.02` you can try setting `off_thresh` to a value that's larger than that. 79 | 80 | ### Open an Issue 81 | 82 | If you've tried some or all of these things and still get flickering, consider opening an issue. 83 | Make sure to include as much information about your setup as you can, including the specific dimmer board you're using and the code you are using to drive it. 84 | If you have access to an oscilliscope, please include screenshots (or if you must, phone pictures of the screen), showing the mains voltage input, the mains voltage output, and the arduino's sync input and trigger output pins at the arduino. (If you only have two channels rather than four, the most important two signals to examine are the sync input and the mains voltage output.) 85 | 86 | ## Theory of Operation 87 | 88 | For those having trouble with this library, understanding the underlying theory of operation may be helpful. 89 | For others, if you're looking to get into programming microcontrollers at the register level, this library might actually be a good example codebase to study. 90 | 91 | Either way, I'd highly recommend looking through the [Atmega328p datasheet](https://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-7810-Automotive-Microcontrollers-ATmega328P_Datasheet.pdf), specifically chapter 15: 16-bit Timer/Counter1 with PWM. This library uses most of the features of this pherhipheral, and that datasheet is the primary source of truth for how it works. 92 | 93 | The library uses Timer/Counter 1 in free-running aka "Normal" mode, where the counter is allowed to count up continuously and overflow from 0xFFFF back to 0x0000. It's set to run from the system clock, with a divide-by-8 prescaler that ensures that the counter's 16 bits are enough to represent the period between zero-crossings and avoid aliasing between overflows. 94 | 95 | With the most common 328p Arduino boards with external 16 MHz crystals, (e.g. an Uno, Micro, Nano, Leonardo), each count represents _approximately_ 0.5us, and the timer overflows back to 0 approximately every 33ms. On other boards that use the 328p's own internal 8 MHz oscillator, each count represents a nominal 1us, for an overflow about every 65ms -- but operating under conditions that put it closer to the edges of the ±14% tolerance, each count could represent anything from 0.86us to 1.14us, and the overflows could be anywhere from 57ms to 76ms. 96 | Importantly, it doesn't actually matter how long the timer counts are -- the "timer count" is the fundamental unit of time being measured by this timer for the purposes of this library, and there's no actual need to relate that unit to more conventional units of time like milliseconds or microseconds, as long as the events being measured are more frequent than the overflow. 97 | 98 | For comparison, on 50Hz power there are 100 zero-crossings per second, so the time between those events is 10ms; whereas on 60Hz power there are 120 so the time between those events is 8.3ms. Either way, the time between events is enough smaller than the overflow period to avoid aliasing. 99 | 100 | The core functionality of this library revolves around the interplay between the counter's Input Capture unit and the Output Compare units when used in free-running normal mode. 101 | 102 | The Input Capture unit is a piece of hardware that, when triggered by an external pin change, instantly copies the current value of the counter to its `ICR1` register. 103 | The Output Compare units have a similar function, but in reverse; they continuously wait and check for the counter to reach the value programmed into their `OCR1` register (`OCR1A` for unit A, `OCR1B1` for unit B), and then instantly change the value of the associated pin. 104 | 105 | The value captured by the input capture unit acts as something of a timestamp; it can be compared to work out the time between events by subtracting a previous timestamp, or used to calculate a value to set the output compare register to to generate an output after a precise duration. 106 | 107 | Both of those concepts -- comparing capture timestamps and computing output timestamps -- are used by this library. Probably the easiest-to-follow examples of this are in the [`TIMER1_CAPT` interrupt service routine](https://github.com/AJMansfield/TriacDimmer/blob/master/src/TriacDimmer.cpp#L147-L173). 108 | 109 | The comparison between captured timestamps happens on [lines 163-164](https://github.com/AJMansfield/TriacDimmer/blob/master/src/TriacDimmer.cpp#L163-L164): 110 | ``` 111 | TriacDimmer::detail::period = ICR1 - last_icr; 112 | last_icr = ICR1; 113 | ``` 114 | 115 | `TriacDimmer::detail::period` is a variable that the library uses to store the measured half-wave period, in timer-count units, and communicate that value from the ISR context to what I'll call the "userland" half of the library. 116 | 117 | And calculating and setting the output timestamps happens a few lines earlier, [lines 152-153](https://github.com/AJMansfield/TriacDimmer/blob/master/src/TriacDimmer.cpp#L152-L153): 118 | ``` 119 | OCR1A = ICR1 + TriacDimmer::detail::ch_A_up; 120 | OCR1B = ICR1 + TriacDimmer::detail::ch_B_up; 121 | ``` 122 | 123 | `TriacDimmer::detail::ch_A_up` and `ch_B_up` are variables that the library uses to store how long the pause between the zero crossing and start of trigger pulse should be, in timer-count units, and communicate that value from the "userland" half of the library to the ISR. 124 | (The library also has `TriacDimmer::detail:ch_A_dn` and `ch_B_dn` that are used in the output compare service routines, to set up the timer to end the trigger pulse at the appropriate time once the pulse has started; this works almost the same but with some further complications around needing to buffer this value to avoid a data race.) 125 | 126 | The "userland" end of that communication can be seen in [`TriacDimmer::detail::setChannelA`](https://github.com/AJMansfield/TriacDimmer/blob/master/src/TriacDimmer.cpp#L91-L103) and it's siblings. The code there might not be super readable, due to the `ATOMIC_BLOCK` parts needed to avoid a data race and the logic for ensuring the pulses always end correctly, but if you were to strip out all of that, fundamentally what it's doing is this: 127 | 128 | ``` 129 | void TriacDimmer::detail::setChannelA(float value){ 130 | TriacDimmer::detail::ch_A_up = TriacDimmer::detail::period * value; 131 | } 132 | ``` 133 | 134 | This operation is the key to the library's ability to compensate for different mains and clock frequencies. And the use of the _measured_ period ensures that the pulse will be proportional to the actual mains frequency, however many timer-counts its period happens to be. And because both the period and pulse offset are measured in timer-counts, variation in the absolute size of each timer-count cancels out. 135 | 136 | This operation is also the reason for the split between the ISR and "userland" parts of the library. One thing to note, is that the 328p does not have hardware floating point, so an arithmetic operation like this internally involves making a subroutine call into a software floating point routine. This wouldn't necessarily be _too_ expensive to do in an ISR, but in general it's good practice to do as little work as possible in ISRs, and in specific the library's margins for how close to the start/end of a cycle and how short of a pulse it can generate are directly affected by how long its ISRs take to run. So this arithmetic is done in the "userland" portion. 137 | 138 | Because of this, though, this recalibration doesn't happen automatically the way the interrupt-handling and pulse-scheduling parts do; in order to get the library to re-calibrate against any drift in the system clock frequency or mains frequency, these "userland" routines need to be called again, and in theory called regularly in order to _keep_ recalibrating. 139 | 140 | In the examples, the main code loops continuously, calling `setBrightness()` regularly (about every 20ms in basic_example.ino, and continuously as it's polling the analog input in potentiometer.ino). Though it doesn't necessarily need to be called continuously like that, it does need to be called at some point _after_ the system has managed to capture and measure a pair of actual zero-crossing events -- i.e. a couple dozen milliseconds after the initial `TriacDimmer::begin()` call. 141 | -------------------------------------------------------------------------------- /examples/basic_example/basic_example.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Basic Example. 3 | 4 | This sketch alternately fades two lights in and out, using a 5 | digital mains AC dimmer switch board. 6 | 7 | This sketch is meant to be used with one of these boards, or 8 | something similar: 9 | https://www.amazon.com/Dimmer-Module-Controller-Arduino-Raspberry/dp/B06Y1GVG26 10 | https://mdwdz.en.alibaba.com/product/60670737878-804998378/2CH_AC_LED_Light_Dimmer_Module_Controller_Board.html 11 | http://www.inmojo.com/store/krida-electronics/item/2-channel-ac-led-bulb-dimmer-module-v2/ 12 | 13 | While this sketch is meant to be used with a dual-channel dimmer, 14 | it can also control just a single channel (just leave the second 15 | channel disconnected). 16 | 17 | Note that the circuit here uses high-voltage mains AC power - make 18 | sure you understand the risks and take appropriate precautions. 19 | 20 | The circuit: 21 | * Pin 8 is connected to the dimmer 'sync' pin. 22 | * Pin 9 is connected to the dimmer 'ch 1' pin. 23 | * Pin 10 is connected to the dimmer 'ch 2' pin. 24 | * The dimmer power input is connected to mains AC power. 25 | * The dimmer channel 1 and channel 2 outputs are connected 26 | to lightbulbs or other devices. 27 | 28 | Created 2017-02-23 29 | By Anson Mansfield 30 | 31 | */ 32 | 33 | #include 34 | 35 | // arduino pins 36 | unsigned char sync = 8; //sync pin 37 | unsigned char channel_1 = 9; // channel 1 pin 38 | unsigned char channel_2 = 10; // channel 2 pin 39 | 40 | void setup() { 41 | // initialize the dimmer library. 42 | TriacDimmer::begin(); 43 | } 44 | 45 | void loop() { 46 | // gradually increase brightness over time 47 | for(float brightness = 0.00; brightness < 1.00; brightness += 0.01){ 48 | 49 | // set channel 1 to the brightness value: 50 | TriacDimmer::setBrightness(channel_1, brightness); 51 | 52 | // invert brightness for channel 2: 53 | TriacDimmer::setBrightness(channel_2, 1 - brightness); 54 | 55 | delay(20); 56 | } 57 | 58 | // and back down - decrease brightness over time 59 | for(float brightness = 1.00; brightness > 0.00; brightness -= 0.01){ 60 | 61 | // set channel 1 to the brightness value: 62 | TriacDimmer::setBrightness(channel_1, brightness); 63 | 64 | // invert brightness for channel 2: 65 | TriacDimmer::setBrightness(channel_2, 1 - brightness); 66 | 67 | delay(20); 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /examples/basic_example/potentiometer.ino: -------------------------------------------------------------------------------- 1 | /* 2 | *Code to control brightness via a potentiometer. In this example the pot is plugged into A0 3 | *Tested on a Robotdyn AC Dimmer 4 | *Code and tutorial to use floating point values with the map function here: https://arduinogetstarted.com/tutorials/arduino-potentiometer 5 | */ 6 | 7 | #include 8 | 9 | float floatMap(float x, float in_min, float in_max, float out_min, float out_max) { 10 | return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; 11 | } 12 | 13 | unsigned char sync = 8; //sync pin 14 | unsigned char channel_1 = 9; // channel 1 pin 15 | 16 | void setup() { 17 | // initialize the dimmer library. 18 | TriacDimmer::begin(); 19 | } 20 | 21 | void loop() { 22 | // read the input on analog pin A0: 23 | int analogValue = analogRead(A0); 24 | float brightness = floatMap(analogValue, 0, 1023, 0, 1); 25 | // set channel 1 to the brightness value: 26 | TriacDimmer::setBrightness(channel_1, brightness); 27 | } 28 | -------------------------------------------------------------------------------- /fritzing.fzz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AJMansfield/TriacDimmer/050583fa1b742b742537774101cd3b847a820a06/fritzing.fzz -------------------------------------------------------------------------------- /fritzing.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AJMansfield/TriacDimmer/050583fa1b742b742537774101cd3b847a820a06/fritzing.png -------------------------------------------------------------------------------- /keywords.txt: -------------------------------------------------------------------------------- 1 | ####################################### 2 | # Syntax Coloring Map 3 | ####################################### 4 | 5 | ####################################### 6 | # Classes and datatypes (KEYWORD1) 7 | ####################################### 8 | TriacDimmer KEYWORD1 9 | detail KEYWORD1 10 | 11 | ####################################### 12 | # Methods and functions (KEYWORD2) 13 | ####################################### 14 | begin KEYWORD2 15 | end KEYWORD2 16 | setBrightness KEYWORD2 17 | getCurrentBrightness KEYWORD2 18 | disable KEYWORD2 19 | 20 | ###################################### 21 | # Constants/defines (LITERAL1) 22 | ####################################### 23 | -------------------------------------------------------------------------------- /library.properties: -------------------------------------------------------------------------------- 1 | name=TriacDimmer 2 | version=1.1.0 3 | author=Anson Mansfield 4 | maintainer=Anson Mansfield 5 | sentence=A library for controlling a triac dimmer. 6 | paragraph=Uses the advanced capabilities of the Timer 1 perhipheral to offload all timing code from the CPU, resulting in much more accurate timing than is possible normally. 7 | category=Device Control 8 | url=https://github.com/AJMansfield/TriacDimmer 9 | architectures=avr 10 | includes=TriacDimmer.h 11 | -------------------------------------------------------------------------------- /src/TriacDimmer.cpp: -------------------------------------------------------------------------------- 1 | #include "TriacDimmer.h" 2 | #include 3 | #include 4 | #include 5 | 6 | uint16_t TriacDimmer::detail::pulse_length; 7 | uint16_t TriacDimmer::detail::min_trigger; 8 | float TriacDimmer::detail::on_thresh; 9 | float TriacDimmer::detail::off_thresh; 10 | 11 | volatile bool TriacDimmer::detail::ch_A_en; 12 | volatile uint16_t TriacDimmer::detail::ch_A_up; 13 | volatile uint16_t TriacDimmer::detail::ch_A_dn; 14 | volatile uint16_t ch_A_dn_buf; 15 | 16 | volatile bool TriacDimmer::detail::ch_B_en; 17 | volatile uint16_t TriacDimmer::detail::ch_B_up; 18 | volatile uint16_t TriacDimmer::detail::ch_B_dn; 19 | volatile uint16_t ch_B_dn_buf; 20 | 21 | uint16_t last_icr = 0; 22 | volatile uint16_t TriacDimmer::detail::period = 16667; 23 | 24 | 25 | void TriacDimmer::begin(uint16_t pulse_length, uint16_t min_trigger, float on_thresh, float off_thresh){ 26 | // Don't need atomic writes since the ISRs haven't started yet. 27 | TriacDimmer::detail::pulse_length = pulse_length; 28 | TriacDimmer::detail::min_trigger = min_trigger; 29 | TriacDimmer::detail::on_thresh = on_thresh; 30 | TriacDimmer::detail::off_thresh = off_thresh; 31 | 32 | TCCR1A = 0; 33 | TCCR1B = _BV(ICNC1) //input capture noise cancel 34 | | _BV(ICES1) //positive edge 35 | | _BV(CS11); // /8 prescaler 36 | 37 | pinMode(8, INPUT); 38 | 39 | TIFR1 = _BV(ICF1); //clear IC interrupt flag 40 | TIMSK1 = _BV(ICIE1); //enable input capture interrupt 41 | } 42 | 43 | void TriacDimmer::end(){ 44 | TIMSK1 = 0; //disable the interrupts first! 45 | TIFR1 = 0xFF; //clear all flags 46 | TCCR1A = 0; //clear to reset state 47 | TCCR1B = 0; 48 | } 49 | 50 | void TriacDimmer::setBrightness(uint8_t pin, float value){ 51 | assert(pin == 9 || pin == 10); 52 | 53 | if (value > TriacDimmer::detail::on_thresh) { 54 | digitalWrite(pin, HIGH); 55 | TriacDimmer::disable(pin); 56 | } else if (value < TriacDimmer::detail::off_thresh) { 57 | digitalWrite(pin, LOW); 58 | TriacDimmer::disable(pin); 59 | } else { 60 | if ((pin & 0x01) == 0x01){ // if (pin == 9){ 61 | TriacDimmer::detail::setChannelA(1 - value); 62 | TriacDimmer::detail::ch_A_en = true; 63 | } else { // if (pin == 10){ 64 | TriacDimmer::detail::setChannelB(1 - value); 65 | TriacDimmer::detail::ch_B_en = true; 66 | } 67 | } 68 | pinMode(pin, OUTPUT); // only set to output once configured. 69 | } 70 | 71 | void TriacDimmer::disable(uint8_t pin) { 72 | assert(pin == 9 || pin == 10); 73 | 74 | if ((pin & 0x01) == 0x01){ // if (pin == 9){ 75 | TriacDimmer::detail::disableChannelA(); 76 | } else { // if (pin == 10){ 77 | TriacDimmer::detail::disableChannelB(); 78 | } 79 | } 80 | 81 | float TriacDimmer::getCurrentBrightness(uint8_t pin){ 82 | assert(pin == 9 || pin == 10); 83 | 84 | if ((pin & 0x01) == 0x01){ // if (pin == 9){ 85 | return 1 - TriacDimmer::detail::getChannelA(); 86 | } else { // if (pin == 10){ 87 | return 1 - TriacDimmer::detail::getChannelB(); 88 | } 89 | } 90 | 91 | void TriacDimmer::detail::setChannelA(float value){ 92 | uint16_t p, u, d; 93 | ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { 94 | // Don't need atomic read for pulse_length or min_trigger since they're not updated from an ISR. 95 | p = TriacDimmer::detail::period; 96 | } 97 | u = p * value; 98 | d = constrain(u + TriacDimmer::detail::pulse_length, TriacDimmer::detail::min_trigger, p); 99 | ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { 100 | TriacDimmer::detail::ch_A_up = u; 101 | TriacDimmer::detail::ch_A_dn = d; 102 | } 103 | } 104 | 105 | void TriacDimmer::detail::setChannelB(float value){ 106 | uint16_t p, u, d; 107 | ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { 108 | // Don't need atomic read for pulse_length or min_trigger since they're not updated from an ISR. 109 | p = TriacDimmer::detail::period; 110 | } 111 | u = p * value; 112 | d = constrain(u + TriacDimmer::detail::pulse_length, TriacDimmer::detail::min_trigger, p); 113 | ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { 114 | TriacDimmer::detail::ch_B_up = u; 115 | TriacDimmer::detail::ch_B_dn = d; 116 | } 117 | } 118 | 119 | float TriacDimmer::detail::getChannelA(){ 120 | uint16_t p, u; 121 | ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { 122 | p = TriacDimmer::detail::period; 123 | u = TriacDimmer::detail::ch_A_up; 124 | } 125 | return (float)p / u; 126 | } 127 | 128 | float TriacDimmer::detail::getChannelB(){ 129 | uint16_t p, u; 130 | ATOMIC_BLOCK(ATOMIC_RESTORESTATE) { 131 | p = TriacDimmer::detail::period; 132 | u = TriacDimmer::detail::ch_B_up; 133 | } 134 | return (float)p / u; 135 | } 136 | 137 | void TriacDimmer::detail::disableChannelA(){ 138 | TriacDimmer::detail::ch_A_en = false; 139 | TCCR1A &=~ _BV(COM1A0) | _BV(COM1A1); 140 | } 141 | 142 | void TriacDimmer::detail::disableChannelB(){ 143 | TriacDimmer::detail::ch_B_en = false; 144 | TCCR1A &=~ _BV(COM1B0) | _BV(COM1B1); 145 | } 146 | 147 | ISR(TIMER1_CAPT_vect){ 148 | TIMSK1 &=~ (_BV(OCIE1A) | _BV(OCIE1B)); //clear interrupts, in case they haven't run yet 149 | TCCR1A &=~ (_BV(COM1A0) | _BV(COM1B0)); 150 | TCCR1C = _BV(FOC1A) | _BV(FOC1B); //ensure outputs are properly cleared 151 | 152 | OCR1A = ICR1 + TriacDimmer::detail::ch_A_up; 153 | OCR1B = ICR1 + TriacDimmer::detail::ch_B_up; 154 | ch_A_dn_buf = TriacDimmer::detail::ch_A_dn; 155 | ch_B_dn_buf = TriacDimmer::detail::ch_B_dn; 156 | 157 | TCCR1A |= 158 | ( TriacDimmer::detail::ch_A_en ? _BV(COM1A0) | _BV(COM1A1) : 0 ) | 159 | ( TriacDimmer::detail::ch_B_en ? _BV(COM1B0) | _BV(COM1B1) : 0 ); //set OC1x on compare match, only if enabled 160 | TIFR1 = _BV(OCF1A) | _BV(OCF1B); //clear compare match flags 161 | TIMSK1 |= _BV(OCIE1A) | _BV(OCIE1B); //enable input capture and compare match interrupts 162 | 163 | TriacDimmer::detail::period = ICR1 - last_icr; 164 | last_icr = ICR1; 165 | 166 | if((signed)(TCNT1 - OCR1A) >= 0){ 167 | TCCR1C = _BV(FOC1A); //interrupt ran late, trigger match manually 168 | } 169 | if((signed)(TCNT1 - OCR1B) >= 0){ 170 | TCCR1C = _BV(FOC1B); //interrupt ran late, trigger match manually 171 | } 172 | } 173 | 174 | 175 | ISR(TIMER1_COMPA_vect){ 176 | TIMSK1 &=~ _BV(OCIE1A); //disable match interrupt 177 | TCCR1A &=~ _BV(COM1A0); //clear OC1x on compare match 178 | 179 | OCR1A = last_icr + ch_A_dn_buf; 180 | 181 | if((signed)(TCNT1 - OCR1A) >= 0){ 182 | TCCR1C = _BV(FOC1A); //interrupt ran late, trigger match manually 183 | } 184 | } 185 | 186 | 187 | ISR(TIMER1_COMPB_vect){ 188 | TIMSK1 &=~ _BV(OCIE1B); //disable match interrupt 189 | TCCR1A &=~ _BV(COM1B0); //clear OC1x on compare match 190 | 191 | OCR1B = last_icr + ch_B_dn_buf; 192 | 193 | if((signed)(TCNT1 - OCR1B) >= 0){ 194 | TCCR1C = _BV(FOC1B); //interrupt ran late, trigger match manually 195 | } 196 | } 197 | 198 | -------------------------------------------------------------------------------- /src/TriacDimmer.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file TriacDimmer.h 3 | * @brief Contains header information for the TriacDimmer library. 4 | * @author Anson Mansfield 5 | * @date 2017-02-23 6 | */ 7 | 8 | #ifndef TriacDimmer_h 9 | #define TriacDimmer_h 10 | 11 | #include 12 | 13 | 14 | /** 15 | * @brief Contains all the library functions. 16 | * This namespace contains the library's public API suitable for general use. 17 | * Implementation details and more technical API functions are in TriacDimmer::detail. 18 | */ 19 | namespace TriacDimmer { 20 | 21 | /** 22 | * @brief Initializes the library. 23 | * @param pulse_length How long the trigger pulses should be, in half-microseconds. 24 | * @param min_trigger Minimum offset from beginning of phase to end of trigger pulse to ensure triac latches. 25 | * @param on_thresh Brightness threshold where the light will be turned on completely. >1 means disabled. 26 | * @param off_thresh Brightness threshold where the light will be turned off completely. <0 means disabled. 27 | * This method initializes the library, setting up the timer and enabling the corresponding interrupts. 28 | */ 29 | void begin(uint16_t pulse_length = 20, uint16_t min_trigger = 2000, float on_thresh = 2.0, float off_thresh = 0.01); 30 | 31 | /** 32 | * @brief Stops the library 33 | * This method stops the library, disabling the interrupts and resetting the timer configuration. 34 | */ 35 | void end(); 36 | 37 | /** 38 | * @brief Sets the current brightness. 39 | * @param pin The pin controlling the desired channel. Only pins 9 and 10 are supported. 40 | * @param value The desired brightness, from 0.0 to 1.0. 41 | * This method enables library control of the given output pin and sets the brightness. 42 | */ 43 | void setBrightness(uint8_t pin, float value); 44 | 45 | /** 46 | * @brief Disables and detaches the pin from the library. 47 | * @param pin The pin to relenquish control of. 48 | * This method disables control of the given pin and stops the library from controlling it. 49 | * Note that both pins start disabled; in order to enable them you can call `setBrightness`. 50 | */ 51 | void disable(uint8_t pin); 52 | 53 | /** 54 | * @brief Gets the currently-set brightness. 55 | * @param pin The pin controlling the desired channel. Only pins 9 and 10 are supported. 56 | * This method retrieves the brightness for the channel controlled by the indicated pin. 57 | */ 58 | float getCurrentBrightness(uint8_t pin); 59 | 60 | 61 | /** 62 | * @brief Contains lower-level API functions. 63 | * This namespace contains lower level API functions that can be used to more directly control the 64 | * pulse waveform. 65 | */ 66 | namespace detail { 67 | /** 68 | * @brief Sets channel A phase angle. 69 | * @param value The phase angle, 0.0 fires immediately, 1.0 fires one period later. 70 | * This method directly sets the phase angle used to control brightness on channel A (pin 9). 71 | * Note that this method does not enable the pin if it is disabled. 72 | */ 73 | void setChannelA(float value); 74 | 75 | /** 76 | * @brief Sets channel B phase angle. 77 | * @param value The phase angle, 0.0 fires immediately, 1.0 fires one period later. 78 | * This method directly sets the phase angle used to control brightness on channel B (pin 10). 79 | * Note that this method does not enable the pin if it is disabled. 80 | */ 81 | void setChannelB(float value); 82 | 83 | /** 84 | * @brief Gets channel A phase angle. 85 | * This method directly retrieves the phase angle used to control brightness on channel A (pin 9). 86 | */ 87 | float getChannelA(); 88 | 89 | /** 90 | * @brief Gets channel B phase angle. 91 | * This method directly retrieves the phase angle used to control brightness on channel B (pin 10). 92 | */ 93 | float getChannelB(); 94 | 95 | /** 96 | * @brief Disables channel A. 97 | * This method disables timer control of channel A (pin 9). Set `ch_A_en` to re-enable. 98 | */ 99 | void disableChannelA(); 100 | 101 | /** 102 | * @brief Disables channel B. 103 | * This method disables timer control of channel B (pin 10). Set `ch_A_en` to re-enable. 104 | */ 105 | void disableChannelB(); 106 | 107 | 108 | /** 109 | * @brief Stores the configured pulse length. 110 | */ 111 | extern uint16_t pulse_length; 112 | 113 | /** 114 | * @brief Stores the configured minimum trigger time. 115 | */ 116 | extern uint16_t min_trigger; 117 | 118 | /** 119 | * @brief Stores the configured minimum trigger time. 120 | */ 121 | extern float on_thresh; 122 | 123 | /** 124 | * @brief Stores the configured minimum trigger time. 125 | */ 126 | extern float off_thresh; 127 | 128 | /** 129 | * @brief Stores whether channel A is enabled. 130 | */ 131 | extern volatile bool ch_A_en; 132 | 133 | /** 134 | * @brief Stores the channel A positive edge delay 135 | */ 136 | extern volatile uint16_t ch_A_up; 137 | 138 | /** 139 | * @brief Stores the channel A negative edge delay 140 | */ 141 | extern volatile uint16_t ch_A_dn; 142 | 143 | /** 144 | * @brief Stores whether channel B is enabled. 145 | */ 146 | extern volatile bool ch_B_en; 147 | 148 | /** 149 | * @brief Stores the channel B positive edge delay 150 | */ 151 | extern volatile uint16_t ch_B_up; 152 | 153 | /** 154 | * @brief Stores the channel B negative edge delay 155 | */ 156 | extern volatile uint16_t ch_B_dn; 157 | 158 | /** 159 | * @brief Stores the computed pulse period. 160 | */ 161 | extern volatile uint16_t period; 162 | 163 | } 164 | 165 | namespace util { 166 | 167 | } 168 | }; 169 | 170 | /* @breif This interrupt sets the output pulses to start at the appropriate time. 171 | * 172 | * This interrupt sets the output pulses to begin at the appropriate time, sets up the 173 | * interrupts that will configure the pulse end, and computes the time since the last pulse. 174 | */ 175 | ISR(TIMER1_CAPT_vect); 176 | 177 | /* @breif This interrupt sets the output A pulse to end at the appropriate time. 178 | * 179 | * This interrupt sets the output A pulse to end at the appropriate time, and manually triggers the 180 | * end in case the interrupt ran late. 181 | */ 182 | ISR(TIMER1_COMPA_vect); 183 | 184 | /* @breif This interrupt sets the output B pulse to end at the appropriate time. 185 | * 186 | * This interrupt sets the output B pulse to end at the appropriate time, and manually triggers the 187 | * end in case the interrupt ran late. 188 | */ 189 | ISR(TIMER1_COMPB_vect); 190 | 191 | #endif 192 | --------------------------------------------------------------------------------