Симисторный фазный регулятор мощности

Как подключить дисплей к Ардуино по I2C

Жидкокристаллический дисплей 1602 с I2C модулем подключается к плате Ардуино всего 4 проводами — 2 провода данных и 2 провода питания. Подключение дисплея 1602 проводится стандартно для шины I2C: вывод SDA подключается к порту A4, вывод SCL – к порту A5. Питание LCD дисплея осуществляется от порта +5V на Arduino. Смотрите подробнее схему подключения жк монитора 1602 на фото ниже.

Для занятия нам понадобятся следующие детали:

  • плата Arduino Uno / Arduino Nano / Arduino Mega;
  • LCD монитор 1602;
  • 4 провода «папа-мама».

Подключение LCD 1602 к Arduino UNO через I²C

После подключения LCD монитора к Ардуино через I2C вам потребуется установить библиотеку LiquidCrystal_I2C.h для работы с LCD дисплеем по интерфейсу I2C и библиотека Wire.h (имеется в стандартной программе Arduino IDE). Скачать рабочую библиотеку LiquidCrystal_I2C.h для LCD 1602 с модулем I2C можно на странице Библиотеки для Ардуино на нашем сайте по прямой ссылке с Google Drive.

Скетч для жк дисплея 1602 с I2C

#include Wire.h> // библиотека для управления устройствами по I2C 
#include LiquidCrystal_I2C.h> // подключаем библиотеку для LCD 1602

LiquidCrystal_I2C lcd(0x27,20,2); // присваиваем имя lcd для дисплея 20х2

void setup() // процедура setup
  lcd.init(); // инициализация LCD дисплея
  lcd.backlight(); // включение подсветки дисплея
  lcd.setCursor(0,0); // ставим курсор на 1 символ первой строки
  lcd.print("I LOVE"); // печатаем сообщение на первой строке
  lcd.setCursor(0,1);  // ставим курсор на 1 символ второй строки
  lcd.print("ARDUINO"); // печатаем сообщение на второй строке

void loop() // процедура loop

/* это многострочный комментарий

// изначально процедура void loop() в скетче не используется
lcd.noDisplay(); // выключаем подсветку LCD дисплея
delay(500); // ставим паузу
lcd.display(); // включаем подсветку LCD дисплея
delay(500); // ставим паузу


Пояснения к коду:

  1. библиотека содержит множество команд для управления LCD дисплея по шине I²C и позволяет значительно упростить скетч;
  2. скетч содержит многострочный комментарий , который позволяет закомментировать сразу несколько строк в программе.
  3. перед выводом информации на дисплей, необходимо задать положение курсора командой , где 0 — номер символа в строке, 1 — номер строки.

Step 2 A Word on Inductive Loads Theory

The presented circuit is suited for pure resistive loads such as incandescent lamps. Should you want to use it for inductive loads, then a snubber circuit is necessary. The figure shows the modifications for use with Inductive loads. Mind you, this is not something I tried as I just wanted to dim lamps, but it is based on examples and theory available on the internet. You would have to adapt the provided PCB The top figure shows the circuit as is, for dimming a lamp. It is in all its simplicity just a resistor to trigger the gate via the diac in the optocoupler. The value of 1k may be changed as discussed in the text before. The bottom figure gives an omnipresent circuit for use in inductive loads. It consists of an additional resistor and capacitor. The gate current is below 15mA. If you are using a less sensitive triac to control the inductive load, reduce the resistor from 2.4kΩ to 1.2kΩ, providing more current to drive the triac and increase the capacitor to 200nF. This snubber circuit is there to protect the triac from the high voltage generated from an inductive load. The feedback may cause some problem for non-inductive load. The small leakage can be significant enough to turn on small load (for example a lamp). There are other snubber circuits, e.g. a resistor and capacitor in series directly over the load

Step 15 Dimming a Bit of Theory

Just as a background to this instructable: There are various types of dimmers. What is presented here is a phase-controlled (aka ‘phase-cut’) leading edge (aka «forward phase»)TRIAC dimmer.

Leading Edge DimmersIn this type the dimmer actually cuts parts off the beginning of the sinewave. This is the most widely used type of dimmer as it is ver suitable for TRIACs. After all, A Triac is easy to switch on and it will switch off by itself once there is a zero crossing because the current drops below the gate hold current

Trailing Edge DimmersAlso known as ‘reverse phase control’ dimmers. A trailing edge dimmer is a considerably more complex circuit. The simple circuitry that is common with leading edge types can no longer be used, because most TRIACs cannot be turned off. Gate turn-off (GTO) TRIACs exist, but are far more expensive and less common in the relatively small sizes needed for lighting. To be able to implement a trailing edge dimmer, the switching device must turn on as the AC waveform passes through zero, using a circuit called a zero-crossing detector. After a predetermined time set by the control, the switching device is turned off, and the remaining part of the waveform is not used by the load.

Trailing edge dimmers commonly use a MOSFET, as these require almost no control current and are rugged and reliable. They are also relatively cheap and readily available at voltage ratings suitable for mains operation. Another option is to use an IGBT (insulated gate bipolar transistor), which combines the advantages of both MOSFET and bipolar transistor. These are generally more expensive than MOSFETs. Again, the waveform is ideal, and it is obvious from the actual waveform shown in Figure 9 that there is a significant deviation — especially at full power. This is caused because some of the applied voltage will always be lost because the complex electronics require some voltage to operate.

Most trailing edge dimmers have another useful function — at least when used with incandescent lamps. The circuitry is designed to provide a ‘soft start’, increasing the voltage to the lamp relatively slowly. With incandescent lamps, this almost eliminates ‘thermal shock’ — that brief period at switch-on where the lamp draws around 10 times the normal operating current. Thermal shock is responsible for most early lamp failures — it is rare indeed for any incandescent lamp to fail while it’s on. Failure is almost always at the moment the switch is turned on. By including the soft-start feature lamp life is increased.

Step 4 Arduino Controlled Light Dimmer the Software

As discussed in the previous theoretical page, the software is fairly easy. If you want to develop your own software all you need to do is: Wait for the zerocrossing Wait a specific time between 0 and 9090 microseconds (9090=10.000-10) switch on yr TRIAC Wait for about 10us (that is the time you need to make sure the TRIAC is on) switch off yr TRIAC (in fact, you only remove the triggersignal to the TRIAC, the TRIAC will stay on till the next zerocrossing) I just briefly sketch the flow of the program that I used:

(make sure you read the ‘NOTE’ below)

The zero X-ing signal generates an interrupt. At 50Hz that interrupt is every 10ms or 10.000uS At 60Hz that interrupt is every 8.333 ms or 8333 uS The interrupt routine then switches on the Triac after a specific time. That time is set in the main program loop. As the program varies the dimming from Full to Off in 128 steps (that is just a choice that was made, could be 100 steps as well), at 50 Hz we need the steps to be 75 uS and at 60Hz they need to be 65 uS It works as follows: The interrupt function»zero_crosss_int» gets called every time a zero-crossing is detected, which is 100times/second. It’s only function is to set the time that the Triac is switched on to the value of the variable ‘dimming’ In the main loop of the program the actual value of that variable is set


AC Voltage dimmer with Zero cross detection
Author: Charith Fernanado Adapted by DIY_bloke
License: Creative Commons Attribution Share-Alike 3.0 License.
Attach the Zero cross pin of the module to Arduino External Interrupt pin
Select the correct Interrupt # from the below table 
(the Pin numbers are digital pins, NOT physical pins: 
digital pin 2 =physical pin 4 and digital pin 3 = physical pin 5)
check: interrupts

Pin    |  Interrrupt # | Arduino Platform
2      |  0            |  All -But it is INT1 on the Leonardo
3      |  1            |  All -But it is INT0 on the Leonardo
18     |  5            |  Arduino Mega Only
19     |  4            |  Arduino Mega Only
20     |  3            |  Arduino Mega Only
21     |  2            |  Arduino Mega Only
0      |  0            |  Leonardo
1      |  3            |  Leonardo
7      |  4            |  Leonardo
The Arduino Due has no standard interrupt pins as an iterrupt can be attached to almosty any pin. 

In the program pin 2 is chosen
int AC_LOAD = 3;    // Output to Opto Triac pin
int dimming = 128;  // Dimming level (0-128)  0 = ON, 128 = OFF

void setup()
  pinMode(AC_LOAD, OUTPUT);// Set AC Load pin as output
  attachInterrupt(0, zero_crosss_int, RISING);  // Choose the zero cross interrupt # from the table above

//the interrupt function must take no parameters and return nothing
void zero_crosss_int()  //function to be fired at the zero crossing to dim the light
  // Firing angle calculation : 1 full 50Hz wave =1/50=20ms 
  // Every zerocrossing thus: (50Hz)-> 10ms (1/2 Cycle) 
  // For 60Hz => 8.33ms (10.000/120)
  // 10ms=10000us
  // (10000us - 10us) / 128 = 75 (Approx) For 60Hz =>65

  int dimtime = (75*dimming);    // For 60Hz =>65    
  delayMicroseconds(dimtime);    // Wait till firing the TRIAC  	
  digitalWrite(AC_LOAD, HIGH);   // Fire the TRIAC
  delayMicroseconds(10);         // triac On propogation delay 
				 // (for 60Hz use 8.33) Some Triacs need a longer period
  digitalWrite(AC_LOAD, LOW);    // No longer trigger the TRIAC (the next zero crossing will swith it off) TRIAC

void loop()  {
  for (int i=5; i

About the software: theoretically in the loop you could let variable ‘i’ start from ‘0’. However, since the timing in the interrupt is a bit of an approximation using ‘0’ (fully on) could screw up the timing a bit. the same goes for 128 (Full off) though that seems to be less critical. Wether ‘5’ or perhaps ‘1’ is the limit for your set up is a matter of trying, your range may go from e.g. 2 to 126 instead of 0-128. If anybody has a more precise way to set up the timing in the interrupt I’d be happy to hear it. Ofcourse it is not necessary to work with interrupts. It is also possible to keep polling the zero crossing pin for going to 0. Though the software works with an interrupt to determine the moment of zero crosssing, it is still not so efficient because the time (dimtime) we need to wait after the zero crossing before the triac is fired is literally spent ‘waiting’ in the zero cross interrupt function.

It would be more efficient to set a timer interrupt to fire at the right moment so in the mean time the arduino can do something else. Such a program can be found in step 6


Let me just reiterate the above statement: This program is a demo of how you can control the dimmer. It is NOT and efficient program as it spends most of its time waiting. It is therefore NOT the most suitable to combine with other tasks of the processor. If you need a more efficient program use a timer instead of delay

Step 11 8051 Controlled Lightdimmer Software

Obviously, one can use the 8051 microcontroller series as well to control the dimmer. As I dont have an 8051 development system anymore, I cannot test any code, but should you want to develop this for an 8051, the following example may be of help:

//Controlling AC with a 8051
//Untested Code
//Compiles with MicroC Pro for 8051
int dimming;
int x;
int i;

void ex0_isr(void) iv IVT_ADDR_EX0 ilevel 0 ics ICS_AUTO {
int dimtime=(75*dimming);
P0=0xFF; // sets entire PORT 0 high, can also use e.g. P0_1 =1 ;
delay_us(10); //propagationdelay

void delay(int maal){
for (x=1; x

Step 13 Problems

If for whatever reason the circuit you built is not working, other than it starting to smoke. Before you do any work on the circuit UNPLUG IT FROM THE MAINS!! There are mainly 3 things that can happen:1-The lamp is flickering This is probably the most common problem you can encounter and there maybe several reasons for it e.g. -a ‘dirty’ powersupply. If your powersupply gives off a lot of extra spikes, these can be present on the 0X signal pin and mess up the clean Zero crossing signals. Try another powersupply. -‘timing’ problems using an optocoupler gives a precise zero-crossing signal, but it is not extremely narrow. The pulse width of this circuit (at 50Hz) is typically around 600us (0.6ms) which sounds fast enough. The problem is that at 50Hz each half cycle takes only 10ms (8.33ms at 60Hz), so the pulse width is over 5% of the total period. This is why most dimmers can only claim a range of 10%-90% — the zero crossing pulse lasts too long to allow more range. The solution is to avoid regulating all the way down or all the way up. Also increasing or sometimes decreasing the step-value (the number 75 for 50Hz and 65 for 60Hz) may cure that.2-The lamp is constantly on This might be a software or a hardware problem and the easiest way to sort that out is to make sure the microcontroller is not connected to the circuit. If the lamp is still on there are grossly 4 possibilities: -You somehow fucked up the circuit, check if it is indeed OK and that everything is connected to where it shoudl be connected. -The MOC3021 is somehow receiving a positive input, make sure there are no stray drops of solder shorting things that shouldn’t be shorted. Short the input and ground wire and see if the lamp stays off. -The MOC3021 is short circuited at the high voltage end. Remove the MOC3021 from its socket and see what happens: if yr lamp stays off there is likely something wrong with yr MOC3021. If your lamp stays on, you probably have a faulty TRIAC -You have a faulty TRIAC. As described above. Yet, check the gate resistor if it really has the correct value, just to make sure3-The lamp is constantly off As this may also be a software or hardware problem, first see what hapens with the arduino disconnected. Connect the input to a plus 5Volt supply and measure the voltage on the primary side of the optocoupler (YOUR CIRCUIT SHOULD NOT BE CONNECTED TO THE MAINS). If that is a couple of volts, connect your circuit to the mains and see what happens. If the lamp switches on there is a problem with the input signal. If it stays off, you may have a faulty optocoupler, a faulty TRIAC or your circuit somehow is not connected to the mains. Another possibility is that the voltage drop over the LED is preventing the optocoupler to open, especially when you are using say 3.3 V as a driving voltage. Make sure you have an LED with a low voltage drop or replace it by a wire bridge.A piece of code that can help you test the Triac circuit is to add the following into the setup

void setup(){ pinMode(AC_LOAD, OUTPUT); // Set the AC Load as output for (int i=0; i digitalWrite(AC_LOAD, HIGH); // triac firing delay(1000); digitalWrite(AC_LOAD, LOW); // triac Off delay(1000); } }This will first fire the TRIAC a few times so you can see it is working

Most common fault till now

From all the people that contacted me about problems of the circuit not working, the most common fault was: faulty wiring: a chip put upside down, a solder joint not good, a wire not connected right.

Step 5 Arduino Controlled Lightdimmer the Software II

I found another piece of Software that allows controlling the lamp via the serial port.It triggers on the falling edge of the zero-crossing signal, so the timing is a bit different.

I have not tested it myself yet, but I see reasons why it should not work: as far as i can see it doesnt receive the number typed in the serial port but it receives the ascii value of each digit that is typed, so a ‘0’ will be seen as 48

int AC_pin = 3;//Pin to OptoTriac
byte dim = 0; //Initial brightness level from 0 to 255, change as you like!

void setup() {
  pinMode(AC_pin, OUTPUT);
  attachInterrupt(0, light, FALLING);//When arduino Pin 2 is FALLING from HIGH to LOW, run light procedure!

void light() {
  if (Serial.available()) {
    dim = Serial.read();
    if (dim  254) { //Turn TRIAC completely ON if dim is 255
      digitalWrite(AC_pin, HIGH);

  if (dim > 0 && dim

Just a note: The above software is not mine. I think it is better to keep the check of the serial port out of the interrupt. Also the 500uS delay before the TRIAC is switched OFF is maybe a bit long.

Step 12 PIC Controlled Lightdimmer the Software

A good article on zero crossing detection with a PIC can be found here:

void interrupt(){ if (INTCON.INTF){ //INTF flag raised, so external interrupt occured ZC = 1; INTCON.INTF = 0; } }

void delay(int maal){ for (x=1; x delay_us(75); // 65 for 60Hz } }

void main() { PORTB = 0; TRISB = 0x01; //RB0 input for interrupt PORTA = 0; ADCON1 = 7; //Disable ADC TRISA = 0xFF; //Make all PORTA inputs PORTD = 0; TRISD = 0; //PORTD all output OPTION_REG.INTEDG = 0; //interrupt on falling edge INTCON.INTF = 0; //clear interrupt flag INTCON.INTE = 1; //enable external interrupt INTCON.GIE = 1; //enable global interrupt

while (1){ if (ZC){ //zero crossing occurred delay(dimming); // ’20’ is an example PORTD.B0 = 1; //Send a pulse delay_us(250); PORTD.B0 = 0; ZC = 0; } } }

Step 14 The Gate Resistor a Bit of Theory

When cruyising the internet for Triac switches, you may have come across a large diversion in the value of the gate resistor value. My choice usually is to take the lowest value that will still protect the gate and the optocoupler. Reader Mali Lagunas did some research in the theory behind the criteria to choose the value of the gate resistor. Which i will copy below: The resistor when placed in this circuit, will have two main effects: a) It will limit/provide the current going into the gate of the triac (I_{GT}) b) It will cause the voltage to drop when the triac is on (V_R) The lowest value this resistor may have (for 220 V AC) is R=220*sqrt(2)/I_{TMS}, where I_{TMS} is the maximum peak current allowed in the photocoupler’s phototriac. These are surge values, thus they are transient and account for a limit before breakdown. Therefore in your circuit R would be R=220*sqrt(2)/1=311.12 or 330 ohms, since the MOC3021′s I_{TMS}=1A. This is consistent with I_{GM} which is the peak gate current of the TIC206. In your schematic you use 1K which would limit the current to 311mA. This “surge” case may take place only when a pulse is received by the phototriac and it is able to conduct I_{GT}, and of course for a line value of 220*sqrt(2). Charge will then accumulate in the triac’s gate until V_{GT} gets build up and the the triac gets activated. In quadrant I, ( V_{GT} and A1 are more positive than A2) in order for sufficient charge to build up and V_{GT} in the main triac to bee reached, the voltage across the triac must equal V_R+V_{TM}+V_{GT} Of course V_R=I_{GT}*R . Commonly, V_{TM}+V_{GT} will both account for approximately 3V (datasheet). At the same time, the resistor must provide sufficient current to the Triac’s gate, let’s say a minimum of 25 mA (sensitivity of the Triac), thus V_{triac}= 330ohms*25mA+1.3V+1.1V=10.65V and V_{triac}= 1k-ohms*25mA+1.3V+1.1V=27.4V (the value in your circuit) Which is the voltage needed to activate the triac. Therefore, the smaller the resistor the less voltage is required to switch on the main triac. What goes on afterwards is mainly that there is a voltage drop across A1 and A2 and therefore the phototriac voltage and current will drop causing turn-off state (of the phototriac). The main triac will be kept switched on if the holding current I_H is respected. When the load current is below I_H, the main triac is switched off until a pulse from the photodiode is emitted again in order to polarize V_{GT} and build the required charge in the next cycle. Q1 and Q3 are the quadrants for this setup.

Step 16 Zero Crossing a Bit of Theory

Though I described the zerocrossing already, I will spend some more words on it. With the ‘bridge and opto-coupler’ circuit that I used in this project, the principle is very clear: A mains AC voltage passes through 2 resistors of 33k and is rectified by the diode bridge.This rectification results in a pulsating DC voltage that keeps the optocoupler open, keeping the zerocrossing signal LOW till the voltage drops to ‘zero’ at what point the optocoupler will not be in conduction anymore and the zerocrossing signal is pulled high, untill the voltage rises again enough to send the optocoupler into conduction again, resulting in the zerocrossing pin going LOW.The ‘quality’ of that zerocrossing pulse is of course depending on a number of factors but mainly on the speed of the optocoupler, the value of the collector resistor, but not in the least on the value of the two resistors in the mains line.

If that value is too low, your optocoupler will burn out, but if it is too high, the voltage at which there still is enough current going through the optocoupler to keep it conducting becomes higher and higher. That means that if the resistor value is too high, the switching of the optocoupler will happen higher on the rising and descending flank of the sin wave, resulting in a wide zerocrossing signal, that starts way before the actual zerocrossing until way after the zerocrossing.Ergo: The resistor value should be as low as possible. In practice however I found the 2x 33k to be a good value, leading to a pulse starting abt 200uS before the actual zerocrossing. That is very acceptable. The current through the 4N25 is approximately 3.33 mA. Surely we could take that up a notch, but it isn’t necessary. With these values the idle use of this circuit is an estimated 0.7 Watts

The same actually goes for the circuit with the H11AA1. The advantage of the H11AA1 is that one doesn’t need a diode bridge as it has two antiparallel diodes. The same goes for the IL250 series or the LTV814One can reach the same effect with two regular optocouplers such as the 4N25, as the figure shows or with a dual optocoupler.I also provided a circuit in which the width of the zerocrossing pulse can be regulated.As said before, the width of the Zerocrossing signal determines how far before the actual zerocrossing the interrupt is generated. Ideally, if you know how wide your zerocrossing signal is, you could take that into account in the software. Suppose your signal is 600uS wide and suppose that is a evenly divided timing. Then you know that your interrupt is generated some 300uS before the actual Zerocrossing. You could wait that period after each interrupt to get a more precise handling of the zerocrossing

Часы реального времени DS3231SN ZS-042. Подключение к Arduino

22.12.16 14:16

Многие устройства требуют постоянного учёта хронометрических данных (дата, время), эту функцию выполняют специальные электронные схемы, которые называются часами реального времени. Часы реального времени, в нынешнее время, реализованы в виде отдельной микросхемы, к которой нужно добавить кварцевый резонатор и автономный источник питания. В некоторых микросхемах, кварцевый резонатор встроен внутри. Одни из таких часов на микросхеме DS3231SN я купил для своих проектов. В примере буду подключать часы реального времени к китайскому аналогу Arduino UNO.

Представляют из себя законченный модуль ZS-042, который можно подключать к различным устройствам, не только к платформе Arduino.

Модуль построен на микросхеме DS3231SN, которая по сути и является часами реального времени. В отличии от старой модели часов, например на микросхеме DS1307, эти часы содержат внутренний кварцевый резонатор, благодаря чему часы имеют точный ход.

Реализовать часы на Arduino можно и без DS3231SN, но тогда при пропадании питания, значения таймера сбрасываются. Эти же часы имеют резервное питание, поэтому при пропадании питания, они продолжают дальше работать.

Часы умеют производить подсчёт часов, минут, секунд, дат, месяцев, лет (високосные года учитываются до 2100 года). Работают в 12 или 24 часовом режиме, содержат два будильника, а так же имеют внутренний термометр, с диапазоном от -40 ° C до + 85 ° C. Для подключения к различным устройствам, часы подключаются по I2C интерфейсу.

Расположение и назначение пинов на модуле ZS-042:

32К —

SQW — Программируемый выход Square-Wave сигнала.

SCL – Через этот пин по интерфейсу I2C происходит обмен данными с часами.

SDA – Через этот пин передаются данные с часов.

VCC – Питание часов реального времени, нужно 5 вольт. Если на этот пин не поступает напряжение, часы переходят в спящий режим.

GND — Земля.

Для подключения к Arduino UNO, пин SDA часов подключаем к пину A4, а пин SCL к A5. Для питания используются пины GND(-) и VCC(+5v).

Пины SDA и SCL на разных платах Arduino:

Mini A4 A5
Nano A4 A5
Mega2560 20 21
Leonardo 2 3

Установим батарейку CR2032 в часы, такие элементы используются для питания BIOS в компьютерах.

При подключении USB кабеля к Arduino, на часах должен загореться светодиод «POWER» (красный светодиод).

Для того что бы запрограммировать часы через Arduino IDE нужно установить библиотеки.

Скачать библиотеку Time и DS1307RTC.

Последняя библиотека была написана для часов на микросхеме DS1307, но её протоколы взаимодействия совместимы с DS3231, поэтому библиотека подойдёт к нашим часам.

Библиотеки нужно скачать, распаковать и поместить в папку «libraries». При запуске Arduino IDE, они с примерами должны появится в «Образцах».

Устанавливаем Дату и время.

Для этого скопируем данный код в Arduino IDE.

//Подключаем библиотеки:#include  #include  #include void setup()  {setSyncProvider(RTC.get);//Устанавливаем время в формате://Часы, минуты, секунды, день, месяц, годsetTime(13,35,0,22,12,2016);//Применяем:RTC.set(now());}void loop(){delay(100);}

Для корректной настройки нужно изменить данные в строке


В скобках через запятую устанавливаем правильные: часы, минуты, секунды, число, месяц, год. У меня в примере установлено 13 часов 35 минут 0 секунд, 22 декабря 2016 год. Вгружаем скетч в Arduino.

Теперь для того что бы прочитать показания из часов, можно воспользоваться примером: «Файл» — «Образцы» — «DS1307RTC» — «ReadTest» и загрузить его в Arduino.

Далее открываем монитор последовательного порта, нажав на соответствующую кнопку.

В открывшемся окне будет отображаться текущие дата и время. Если отключить питание модуля часов от Arduino, Arduino не сможет отслеживать значения и в мониторе через какое то время появится надпись «…read error!» (выделил красным). После возобновления питания, показания даты и времени будут отсчитываться далее. Показания даты и времени не сбросились, поскольку часы питались от своей батарейки CR2032.

Step 8 Software to Set Level Using Up and Down Buttons

Below a code to set the light level with up and down buttons. It uses a timer that checks for the time necessary to trigger the TRIAC, rather than wait in a delay loop

AC Light Control
Uses up and down buttons to set levels
makes use of a timer interrupt to set the level of dimming
#include            // Avaiable from http://www.arduino.cc/playground/Code/Timer1

volatile int i=0;               // Variable to use as a counter of dimming steps. It is volatile since it is passed between interrupts
volatile boolean zero_cross=0;  // Flag to indicate we have crossed zero
int AC_pin = 3;                 // Output to Opto Triac
int buton1 = 4;                 // first button at pin 4
int buton2 = 5;                 // second button at pin 5
int dim2 = 0;                   // led control
int dim = 128;                  // Dimming level (0-128)  0 = on, 128 = 0ff
int pas = 8;                    // step for count;
int freqStep = 75;              // This is the delay-per-brightness step in microseconds. It allows for 128 steps
                                // If using 60 Hz grid frequency set this to 65

void setup() {  // Begin setup
  pinMode(buton1, INPUT);  // set buton1 pin as input
  pinMode(buton2, INPUT);  // set buton1 pin as input
  pinMode(AC_pin, OUTPUT);                          // Set the Triac pin as output
  attachInterrupt(0, zero_cross_detect, RISING);    // Attach an Interupt to Pin 2 (interupt 0) for Zero Cross Detection
  Timer1.initialize(freqStep);                      // Initialize TimerOne library for the freq we need
  Timer1.attachInterrupt(dim_check, freqStep);      // Go to dim_check procedure every 75 uS (50Hz)  or 65 uS (60Hz)
  // Use the TimerOne Library to attach an interrupt


void zero_cross_detect() {    
  zero_cross = true;               // set flag for dim_check function that a zero cross has occured
  i=0;                             // stepcounter to 0.... as we start a new cycle
  digitalWrite(AC_pin, LOW);

// Turn on the TRIAC at the appropriate time
// We arrive here every 75 (65) uS
// First check if a flag has been set
// Then check if the counter 'i' has reached the dimming level
// if so.... switch on the TRIAC and reset the counter
void dim_check() {                   
  if(zero_cross == true) {              
    if(i>=dim) {                     
      digitalWrite(AC_pin, HIGH);  // turn on light       
      i=0;  // reset time step counter                         
      zero_cross=false;    // reset zero cross detection flag
    else {
      i++;  // increment time step counter                     

void loop() {  
  digitalWrite(buton1, HIGH);
  digitalWrite(buton2, HIGH);
 if (digitalRead(buton1) == LOW)   
  if (dim127) 
  if (digitalRead(buton2) == LOW)   
  if (dim>5)  
     dim = dim - pas;
  if (dim

Add a Comment

Ваш e-mail не будет опубликован.