Добавить кнопку включения в готовый скетч
- Войдите на сайт для отправки комментариев
Пт, 04/01/2019 - 17:32
Всем привет! Подскажите пожалуйста, имеется скетч, некий таймер с разными мигалками, мне нужно добавить к нему кнопку включения и выключения, естественно не фиксируемую, а тактильную. Возможно ли такое ? При необходимости могу предоставить скетч.
#include "LedControl.h" /* pin 12 DataIn pin 11 CLK pin 10 LOAD Two MAX7221's */ LedControl lc=LedControl(12,11,10,2); //buttons and inputs const int button0 = A0; const int button1 = A1; const int button2 = A2; const int button3 = A3; const int pot1 = A4; const int greenpin = 5; //green LED const int redpin = 6; //red LED const int yellowpin = 8; //yellow LED const int emitters = 3; //emitters are connected in serial const int speaker = 4; //piezo const int colons = 13; //colons are connected in serial unsigned long totalsectime = 35; //this value is the beginning countdown time //totalsectime will later be filled in by time set function by inputs void setup() { randomSeed(analogRead(A5)); //sets pin A5 as an input to generate a random number pinMode(colons, OUTPUT); pinMode(speaker, OUTPUT); pinMode(emitters, OUTPUT); pinMode(button0, INPUT); pinMode(button1, INPUT); pinMode(button2, INPUT); pinMode(button3, INPUT); pinMode(pot1, INPUT); pinMode(greenpin, OUTPUT); pinMode(redpin, OUTPUT); pinMode(yellowpin, OUTPUT); // number of devices LedControl int devices=lc.getDeviceCount(); //init all devices in a loop for(int address=0;address<devices;address++) { //take out of power saving mode lc.shutdown(address,false); // set brightness - depends on Rset values lc.setIntensity(0,15); lc.setIntensity(1,1); /* and clear the display */ lc.clearDisplay(address); //sets the number of digits that each 7221 will scan through when multiplexing lc.setScanLimit(0, 6); lc.setScanLimit(1, 6); } } //COLON BLINK FUNCTION for normal countdown 2 blink/second int colonsState = LOW; long previouscolonsMillis = 0; long colonsinterval = 250; void colonBlink(){ unsigned long currentcolonsMillis = millis(); if(currentcolonsMillis - previouscolonsMillis > colonsinterval) { // save the last time you blinked the LED previouscolonsMillis = currentcolonsMillis; // if the LED is off turn it on and vice-versa: if (colonsState == LOW) colonsState = HIGH; else colonsState = LOW; // set the LED with the ledState of the variable: digitalWrite(colons, colonsState); } } //GENSER SEQUENCE PREAMBLE void genserOne() { //GEnSEr //G lc.setRow(0,0,B01011110); //E lc.setChar(0,1,'E',false); //n lc.setRow(0,2,0x15); //S(5) lc.setChar(0,3,'5',false); //E lc.setChar(0,4,'E',false); //r lc.setRow(0,5,0x05); delay(400); //clear lc.clearDisplay(0); delay(40); //random 1 lc.setRow(0,0,B01001001); lc.setRow(0,1,B00010101); lc.setRow(0,2,B00100011); lc.setRow(0,3,B00000011); lc.setRow(0,4,B01010100); lc.setRow(0,5,B01000011); delay(200); //clear lc.clearDisplay(0); delay(40); //CAluri //C lc.setRow(0,0,B01001110); //A lc.setChar (0,1,'A',false); //l(lowercase "L") lc.setRow(0,2,B00110000); //u lc.setRow(0,3,B00011100); //r lc.setRow(0,4,B00000101); //i lc.setRow(0,5,B00010000); delay(200); //clear lc.clearDisplay(0); delay(40); //4th Sequence lc.setRow(0,0,B00100011); lc.setRow(0,1,B00000011); lc.setRow(0,2,B01010100); lc.setRow(0,3,B01000011); lc.setRow(0,4,B00010011); lc.setRow(0,5,B00011001); delay(200); //clear lc.clearDisplay(0); delay(40); //Second CAluri sequence //C lc.setRow(0,0,B01001110); //A lc.setChar (0,1,'A',false); //l(lowercase "L") lc.setRow(0,2,B00110000); //u lc.setRow(0,3,B00011100); //r lc.setRow(0,4,B00000101); //i lc.setRow(0,5,B00010000); delay(200); //clear lc.clearDisplay(0); delay(40); //6th Sequence lc.setRow(0,0,B00101010); lc.setRow(0,1,B00000011); lc.setRow(0,2,B00011010); lc.setRow(0,3,B01001000); lc.setRow(0,4,B01000001); lc.setRow(0,5,B01001001); delay(200); //clear lc.clearDisplay(0); delay(40); //6th Sequence lc.setRow(0,0,B00010011); lc.setRow(0,1,B00011001); lc.setRow(0,2,B00100010); lc.setRow(0,3,B00011000); lc.setRow(0,4,B01000001); lc.setRow(0,5,B00100101); delay(250); //clear lc.clearDisplay(0); delay(75); } void displayFade() { //clear delay(100); //INSERT FUNCTION FOR DIGIT FADING AFTER ZERO lc.setRow(0,0,B01111000); //partially zapped 0 lc.setRow(0,1,B01111110); //0 lc.setRow(0,2,B01111110); //0 lc.setRow(0,3,B01111110); //0 lc.setRow(0,4,B01111110); //0 lc.setRow(0,5,B00011110); //partially zapped 0 delay(30); lc.setRow(0,0,B00110000); //partially zapped 0 lc.setRow(0,1,B01111110); //0 lc.setRow(0,2,B01111110); //0 lc.setRow(0,3,B01111110); //0 lc.setRow(0,4,B10000000); //0 lc.setRow(0,5,B00000110); //partially zapped 0 delay(30); lc.setRow(0,0,B00000000); //fully zapped 0 lc.setRow(0,1,B01111110); //0 lc.setRow(0,2,B01111110); //0 lc.setRow(0,3,B01111110); //0 lc.setRow(0,4,B01111110); //0 lc.setRow(0,5,B00000000); //fully zapped 0 delay(30); lc.setRow(0,0,B00000000); //fully zapped 0 lc.setRow(0,1,B01111000); //partially zapped 0 lc.setRow(0,2,B01111110); //0 lc.setRow(0,3,B01111110); //0 lc.setRow(0,4,B01000000); //partially zapped 0 lc.setRow(0,5,B00000000); //fully zapped 0 delay(30); lc.setRow(0,0,B00000000); //fully zapped 0 lc.setRow(0,1,B00110000); //partially zapped 0 lc.setRow(0,2,B01111110); //0 lc.setRow(0,3,B01111110); //0 lc.setRow(0,4,B00000110); //partially zapped 0 lc.setRow(0,5,B00000000); //fully zapped 0 delay(30); lc.setRow(0,0,B00000000); //fully zapped 0 lc.setRow(0,1,B00000000); //fully zapped 0 lc.setRow(0,2,B01111110); //0 lc.setRow(0,3,B01111110); //0 lc.setRow(0,4,B00000000); //fully zapped 0 lc.setRow(0,5,B00000000); //fully zapped 0 delay(55); lc.setRow(0,0,B00000000); //fully zapped 0 lc.setRow(0,1,B00000000); //fully zapped 0 lc.setRow(0,2,B01111000); //partially zapped 0 lc.setRow(0,3,B01000000); //partially zapped 0 lc.setRow(0,4,B00000000); //fully zapped 0 lc.setRow(0,5,B00000000); //fully zapped 0 delay(30); lc.setRow(0,0,B00000000); //fully zapped 0 lc.setRow(0,1,B00000000); //fully zapped 0 lc.setRow(0,2,B00110000); //partially zapped 0 lc.setRow(0,3,B00000110); //partially zapped 0 lc.setRow(0,4,B00000000); //fully zapped 0 lc.setRow(0,5,B00000000); //fully zapped 0 delay(30); lc.setRow(0,0,B00000000); //fully zapped 0 lc.setRow(0,1,B00000000); //fully zapped 0 lc.setRow(0,2,B00000000); //fully zapped 0 lc.setRow(0,3,B00000000); //fully zapped 0 lc.setRow(0,4,B00000000); //fully zapped 0 lc.setRow(0,5,B00000000); //fully zapped 0 delay(1000); } void displayWrap() { //INSERT DISPLAY WRAP delay(40); lc.setRow(0,0,B00000010); lc.setRow(0,1,B00000010); lc.setRow(0,2,B00000010); lc.setRow(0,3,B00000010); lc.setRow(0,4,B00000010); lc.setRow(0,5,B00000010); delay(40); lc.setRow(0,0,B01000000); lc.setRow(0,1,B01000000); lc.setRow(0,2,B01000000); lc.setRow(0,3,B01000000); lc.setRow(0,4,B01000000); lc.setRow(0,5,B01000000); delay(40); lc.setRow(0,0,B00100000); lc.setRow(0,1,B00100000); lc.setRow(0,2,B00100000); lc.setRow(0,3,B00100000); lc.setRow(0,4,B00100000); lc.setRow(0,5,B00100000); delay(40); lc.setRow(0,0,B00010000); lc.setRow(0,1,B00010000); lc.setRow(0,2,B00010000); lc.setRow(0,3,B00010000); lc.setRow(0,4,B00010000); lc.setRow(0,5,B00010000); delay(40); lc.setRow(0,0,B00001000); lc.setRow(0,1,B00001000); lc.setRow(0,2,B00001000); lc.setRow(0,3,B00001000); lc.setRow(0,4,B00001000); lc.setRow(0,5,B00001000); delay(40); lc.setRow(0,0,B00000100); lc.setRow(0,1,B00000100); lc.setRow(0,2,B00000100); lc.setRow(0,3,B00000100); lc.setRow(0,4,B00000100); lc.setRow(0,5,B00000100); delay(40); lc.setRow(0,0,B00000010); lc.setRow(0,1,B00000010); lc.setRow(0,2,B00000010); lc.setRow(0,3,B00000010); lc.setRow(0,4,B00000010); lc.setRow(0,5,B00000010); delay(40); lc.setRow(0,0,B01000000); lc.setRow(0,1,B01000000); lc.setRow(0,2,B01000000); lc.setRow(0,3,B01000000); lc.setRow(0,4,B01000000); lc.setRow(0,5,B01000000); delay(40); lc.setRow(0,0,B00100000); lc.setRow(0,1,B00100000); lc.setRow(0,2,B00100000); lc.setRow(0,3,B00100000); lc.setRow(0,4,B00100000); lc.setRow(0,5,B00100000); delay(40); lc.setRow(0,0,B00010000); lc.setRow(0,1,B00010000); lc.setRow(0,2,B00010000); lc.setRow(0,3,B00010000); lc.setRow(0,4,B00010000); lc.setRow(0,5,B00010000); delay(40); lc.setRow(0,0,B00001000); lc.setRow(0,1,B00001000); lc.setRow(0,2,B00001000); lc.setRow(0,3,B00001000); lc.setRow(0,4,B00001000); lc.setRow(0,5,B00001000); delay(40); lc.setRow(0,0,B00000100); lc.setRow(0,1,B00000100); lc.setRow(0,2,B00000100); lc.setRow(0,3,B00000100); lc.setRow(0,4,B00000100); lc.setRow(0,5,B00000100); delay(40); lc.setRow(0,0,B00000010); lc.setRow(0,1,B00000010); lc.setRow(0,2,B00000010); lc.setRow(0,3,B00000010); lc.setRow(0,4,B00000010); lc.setRow(0,5,B00000010); delay(40); lc.setRow(0,0,B00000001); lc.setRow(0,1,B00000001); lc.setRow(0,2,B00000001); lc.setRow(0,3,B00000001); lc.setRow(0,4,B00000001); lc.setRow(0,5,B00000001); } void updatespeaker(){ static int state = 0; static unsigned int beeptime = 250; static unsigned int sinterval = 500; static unsigned int freq = 2500; static unsigned long lasttimeon = 0; unsigned long m = millis(); if (state == -1){ lasttimeon = m; state = 1; tone(speaker,1000); noTone(speaker); tone(speaker,1000); return; } if (state == 0){ if (m >= lasttimeon +sinterval){ state = 1; tone(speaker,freq); lasttimeon = m; } return; } if (state == 1){ if (m >= lasttimeon + beeptime){ noTone(speaker); state = 0; beeptime = 100; } return; } } //setting up seconds time conversion #define secondsinaday 86400 //((60*60)*24) #define secondsinhour 3600 //(60*60) #define secondsinminute 60 long countpreviousMillis = 0; //stores count milliseconds long countinterval = 1000; //1 second void displayDate(){ unsigned long countcurrentMillis = millis(); if(countcurrentMillis - countpreviousMillis > countinterval) { // save the last time counted countpreviousMillis = countcurrentMillis; totalsectime--; //decrement of 1 second unsigned long sectime = totalsectime; /*takes the totalsectime variable and converts it inside of this function so that the time conversions do not interfere with the later functions */ unsigned long days = sectime/secondsinaday; //calculates seconds in a day sectime = sectime % secondsinaday; //takes the remainder of the previous calculation unsigned long hours = sectime/secondsinhour; //calculates seconds in an hour sectime = sectime % secondsinhour; //takes the remainder of the previous calculation unsigned long minutes = sectime/secondsinminute; //calculates seconds in a minute unsigned long seconds = sectime % secondsinminute; //takes the remainder, and that is seconds /*below takes the values generated from above and makes variables for each digit to display based on on dividing the values by hundreds/tens/single numbers*/ unsigned long days_hundreds = days/100; unsigned long days_tens = (days %100)/10; unsigned long days_units = (days %100)%10; unsigned long hours_tens = (hours %100)/10; unsigned long hours_units = (hours %100)%10; unsigned long minutes_tens = (minutes %100)/10; unsigned long minutes_units = (minutes %100)%10; unsigned long seconds_tens = (seconds %100)/10; unsigned long seconds_units = (seconds %100)%10; //below is where the magic happens //sends digit to: 7221 device //digit order //variable from above calculations //true/false for the decimal point lc.setDigit(1,0,days_hundreds,false); lc.setDigit(1,1,days_tens,false); lc.setDigit(1,2,days_units,false); lc.setDigit(0,0,hours_tens,false); lc.setDigit(0,1,hours_units,false); lc.setDigit(0,2,minutes_tens,false); lc.setDigit(0,3,minutes_units,false); lc.setDigit(0,4,seconds_tens,false); lc.setDigit(0,5,seconds_units,false); if(sectime==15){ //wrap-around when time reaches 15 seconds displayWrap(); } if(totalsectime <=5 ) { //lights emitter LEDs when time reaches 5 seconds and keeps speaker solid updatespeaker(); digitalWrite(emitters, HIGH); } else{ digitalWrite(emitters, LOW); } /*Below is the "reset" mode that I have worked out right now, but is due to change as I get more things sorted out, and this will do other things. Right now is just for testing/looks.*/ if(totalsectime <= 0){ delay(2500); displayFade(); genserOne(); displayWrap(); updatespeaker(); totalsectime = random(16756131); } } if(totalsectime > 5){ //colon blink function for normal countdown colonBlink(); updatespeaker(); } } void loop() { displayDate(); }Кноаку аключения/выключения чего?
Всей этой программы
подскажите как ?
Кноаку аключения/выключения чего?
всей этой программы.
А потом что? Может просто выключить питание или сделать резет?
подскажите как ?
Ну а чего не подсказать?
В функции loop заведите статическую премеменную типа bool, назовите её, например, niHeraNeDelat. Изначально присвойте ей false.
там же в функции loop, в самом начале, поставьте проверку "если кнопка нажата, то niHeraNeDelat = ! niHeraNeDelat; и дождаться пока кнопка не будет отпущена"
Ну, и наконец, сразу после описанной проверки, поставьте ещё одну "if (niHeraNeDelat) return;"
Собственно всё. Запустили - работает, нажали кнопку - не работает, ещё раз нажаи - снова работает и т.д.
Насчёт дребезга - сами боритесь.
Я так понимаю, что тактильные кнопки - это кнопки срабатывающие с тактильным ощущением, со щелчком. А вот укоренившемуся у нас названию "тактовые" сразу и объяснение не придумаешь.
подскажите как ?
Ну а чего не подсказать?
В функции loop заведите статическую премеменную типа bool, назовите её, например, niHeraNeDelat. Изначально присвойте ей false.
там же в функции loop, в самом начале, поставьте проверку "если кнопка нажата, то niHeraNeDelat = ! niHeraNeDelat; и дождаться пока кнопка не будет отпущена"
Ну, и наконец, сразу после описанной проверки, поставьте ещё одну "if (niHeraNeDelat) return;"
Собственно всё. Запустили - работает, нажали кнопку - не работает, ещё раз нажаи - снова работает и т.д.
Насчёт дребезга - сами боритесь.
спасибо! Попробую это все воплотить !
int switchPin = 8; boolean running = false; void setup() { pinMode(switchPin, INPUT); digitalWrite(switchPin, HIGH); } void loop() { if (digitalRead(switchPin) == LOW) { delay(100); running = !running; } }подскажите как ?
Ну а чего не подсказать?
В функции loop заведите статическую премеменную типа bool, назовите её, например, niHeraNeDelat. Изначально присвойте ей false.
там же в функции loop, в самом начале, поставьте проверку "если кнопка нажата, то niHeraNeDelat = ! niHeraNeDelat; и дождаться пока кнопка не будет отпущена"
Ну, и наконец, сразу после описанной проверки, поставьте ещё одну "if (niHeraNeDelat) return;"
Собственно всё. Запустили - работает, нажали кнопку - не работает, ещё раз нажаи - снова работает и т.д.
Насчёт дребезга - сами боритесь.
Что то подобное нашёл, но наверно не правильно?
Провильно. Осталось вам мелочь - написать код когда "программа работает" и код когда "программа не работает" и просто переключать их.
Провильно. Осталось вам мелочь - написать код когда "программа работает" и код когда "программа не работает" и просто переключать их.
)))) всего ничего... если бы знать как
)))) всего ничего... если бы знать как
Вам же Евгений всё написал. Но реализовано-то у Вас не всё. Ну и добавьте не весь предыдущий код, а какое-нибудь простое действие из одной строчки, например печать в сериал. Чтобы только было видно - вот оно выполняется, а вот нет.
int switchPin = 8; boolean running = false; void setup() { pinMode(switchPin, INPUT); digitalWrite(switchPin, HIGH); } void loop() { if (digitalRead(switchPin) == LOW) { delay(100); running = !running; } }[quote=nero32]
Насчёт дребезга - сами боритесь.
А если кнопку подтянуть к питанию за счет " INPUT_PULLUP " дребезг это победит или нет ?
А если кнопку подтянуть к питанию за счет " INPUT_PULLUP " дребезг это победит или нет ?
Ну, в благодарность за то, что, благодаря Вам, я спор выиграл, отвечу: нет, не победит.
А если кнопку подтянуть к питанию за счет " INPUT_PULLUP " дребезг это победит или нет ?
Ну, в благодарность за то, что, благодаря Вам, я спор выиграл, отвечу: нет, не победит.
Главное, в церкви освятить не забудьте. Хотя, Вы, очевидно, пастафарианец, потом не знаю, как там у Вас освящают.
Читайте, если умеете - https://my.eng.utah.edu/~cs5780/debouncing.pdf