I decided to write a program to automatically close doors in the unit dormitory after 24:00 microcontroller.
Actually I was faced with a huge number of pitfalls, and since articles in order to remove the stones I found, but only an educated bet and articles on foreign websites reached the correct actions, and now that you describe. The mechanisms work, I will not describe. There is nothing complicated. Most in my opinion difficult for me as a beginner will be described in this article.
Job : To make asynchronous clock, to work from one battery of type CR2032 with the fact that the MC needs to sleep sweet sleep and not to eat honey for us current, and when 0:00 the microcontroller woke up changed the state of the legs (gave impetus to the unit and put in zero to e. castle turned) and in 6:00 am back opened, and went to bed. Watch if this work were not behind not on one dolinecount. Imagine the consequences if the mechanism will operate for years, and in the morning not to go outside.
So let us begin. I have a MK Atmega16a-pu (actually almost the same as Atmega16) and with it, the whole scheme will be managed. To enable asynchronous mode we need not only software code, but bought on the radio market Quartz resonator 32 768 Hz I type “match”, can buy any type. You need to connect it to pins 28 and 29 on the site.
So I marked the pins 12 and 13, for added stability you can connect the quartz 4 MHz. And set the fuse bits for external RC oscillator, but it is according to your taste and need. But the fact that the scheme will become more stable and correct it for sure.
Well, there seems to be all on the technical side. We now go to program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
/* * GccApplication1.cpp * * Created: 24.01.2022 15:39:08 * Author: Sokol */ #define F_CPU 1000000 // внутри МК процессор работает с частотой 1 мГц что равно 1 000 000 Гц. Указываем это, но не обязательно. #include <avr/io.h> //стандартная библиотека мк. #include <avr/sleep.h> //подключаем библиотеку сна #include <avr/delay.h> //подключаем задержки #include <avr/interrupt.h> //подключаем прерывания #define SLEEP_MODE_PWR_SAVE (_BV(SM0) | _BV(SM1)) //Заменяем фразу SLEEP_MODE_PWR_SAVE на (_BV(SM0) | _BV(SM1)) , чтобы потом было легче. volatile unsigned char second=0, minute=0, hour=0; //Инициализируем переменные ISR(TIMER2_COMP_vect) //Описываем вектор для нашего асинхронного прерывания (что будет выполняться кварцем.) { second++; if (second == 60) { PORTA = 0x01; //Выставляем в логическую единицу на пин 0. sleep_disable(); // Когда пройдет одна минута прерывание так сказать ущепнет МК, и он проснется сам ! (питание будет в районе 1 мА) second=0; minute++; if (minute==60) { minute=0; hour++; if (hour==24) { hour=0; } } } } int main(void) { DDRA = 0x01; asm("cli"); //Обязательно запрещаем прерывания //Стандартная постановка битов в МК для активации ухода в Асинхронный режим. ASSR |=(1<<AS2); while(ASSR != (0b00001000)) { asm("nop"); } TCCR2 |= (1<<CS21)|(1<<CS22)|(1<<WGM21); OCR2 = 127; TIMSK |= (1<<OCIE2); TIFR = 0; //Постановку окончили. (более детально про установку в асинхрон. можно найти в Даташите.) set_sleep_mode(SLEEP_MODE_PWR_SAVE); //Выбираем тип сна, в нашем случае это будет Power-Saver. sleep_enable(); //Выставляем соответствующие биты в МК. asm("sei"); //Разрешаем прерывания. Обязательно! _delay_ms(1000); //Делаем задержку для того чтобы Кварцевый резонатор (часовой) 32 768 Гц включился в асинхрон.режим. Это обязательно !. Число может быть и 500. Но я выбрал именно одну секунду. Для стабильности. while(1) { for(int a=0; a < 500; a++) // Тут все на ваше усмотрение что сделать до того как МК уйдет в сон. { asm ("nop"); } PORTA = 0x00; //Выставляем пин в логический ноль, чтобы лампочка один раз мигнула когда выйдет из сна if (second == 2) //Когда будет 2 секунды уйдем в сон. { sleep_cpu(); // Уход в сон. Снижение потребления энергии у меня не превышает 35 мкА (микро а не мили, не путать). } } } |
Such action, we have made meager use of electricity, according to my calculations, a battery with 220mA СR2032 will run one year without replacement and recharging. If you connect another power source, for example two double-a batteries, with 2500 mA then you can imagine how much the scheme will work
In my code everything described so, so you saw when he came out of sleep. The signal is not in 24:00 and 6:00, and so that you feel everything is clearly visible. To change the program and make it fully operational need to slightly tweak the code. But I think it will not be difficult.
Good luck ! Hope I helped you !
Was it used for: Atmel Studio 6.0, khazama avr programmer, programmer - usbasp.