I
I
IGOR EZHKOV2021-12-06 22:19:59
Arduino
IGOR EZHKOV, 2021-12-06 22:19:59

How to do without delay in sketch for Arduino?

Help to get around the problem with delay in else. In this form, everything works, but the delay prevents us from processing the button state. Is there a way to flash the red LED differently?

int BuzzPin = 9;   // выход на динамик
int UccBF = 12;   // питание р/с
int Button = 5;   // вход кнопки
int GreenLed = 10;    // выход на зелёный светодиод 
int RedLed = 9;   // выход на красный светодиод 

void setup()
{
pinMode(BuzzPin, OUTPUT);   // устанавливает режим работы - выход
pinMode(UccBF, OUTPUT);   // устанавливает режим работы - выход
pinMode(GreenLed, OUTPUT);    // устанавливает режим работы - выход
pinMode(Button, INPUT);   // устанавливает режим работы - вход
digitalWrite(BuzzPin, HIGH);   // выключает динамик
digitalWrite(UccBF, HIGH);   // выключает питание р/с
digitalWrite(GreenLed, LOW);   // выключает зелёный светодиод
digitalWrite(Button, HIGH);   // включаем подтягивающий резистор
}

void loop() 
{
  if (digitalRead(Button) == LOW) {   // считываем состояние кнопки
    digitalWrite(BuzzPin, LOW); delay(500);   // Включаем звук на 0,5 секунд.
    digitalWrite(BuzzPin, HIGH); delay(5000);   // Выключаем звук на 5 секунд. 
    digitalWrite(UccBF, LOW);   // включаем питание р/с:
    digitalWrite(GreenLed, HIGH);    // зажигаем зелёный светодиод:
    for (int i=0; i <= 5; i++) {
      digitalWrite(BuzzPin, LOW); delay(500);   // Включаем звук на 0,5 секунд
      digitalWrite(BuzzPin, HIGH); delay(500);   // Выключаем звук на 0,5 секунд
    }
    digitalWrite(BuzzPin, LOW); delay(1000);   // Включаем звук на 1 секунду
    digitalWrite(BuzzPin, HIGH);   // выключаем звук
    digitalWrite(UccBF, HIGH);   // выключаем питание р/с
    digitalWrite(GreenLed, LOW);   // выключаем зелёный светодиод
  }
  else {
    // мигаем красным светодиодом
    digitalWrite(RedLed, HIGH); delay(100);
    digitalWrite(RedLed, LOW);  delay(900);
  }
}

Answer the question

In order to leave comments, you need to log in

4 answer(s)
V
vanyamba-electronics, 2021-12-07
@fancarver

In such a short post, such a long answer is quite difficult to place. I can recommend reading my article on the subject of Arduino. How to blink an LED without delay .
Or use the LEDseq library , with which you can set blinking sequences. For example, make it so that when you press a button, the LED blinks three times.

M
Maxim K, 2021-12-06
@mkvmaks

Alexgyver lessons, there is a library for working with buttons and examples for millis

A
AntHTML, 2021-12-07
@anthtml

Option 1 - Replace the delay function with its source code with millis
Option 2 - outweigh the button by 2-3 pins and process it through interrupts

B
Borys Latysh, 2021-12-07
@nava2002

In general, good manners recommend working WITHOUT delay().
Option

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question