Попытка заставить функцию работать (и продолжать работать) при запуске модулем RTC

Итак, я написал некоторый код, который я хочу начать мигать светодиодом, когда время достигает определенного момента каждый день. Светодиод должен продолжать мигать до тех пор, пока не будет нажата кнопка, однако по какой-то причине светодиод перестанет мигать сам по себе, обычно примерно через 1 минуту.

Я не уверен, активируется ли контакт 11 случайным образом или он просто не включает свет после того, как состояние таймера прошло. Ребята, вы знаете, где я ошибаюсь?

#include <DS3231.h>

// Init the DS3231 using the hardware interface
DS3231  rtc(SDA, SCL);
bool active = false;

void setup()
{
  // Setup Serial connection
  Serial.begin(115200);
  // Uncomment the next line if you are using an Arduino Leonardo
  //while (!Serial) {}

  // Initialize the rtc object
  rtc.begin();
  pinMode(12, OUTPUT);
  pinMode(11, INPUT);
  // The following lines can be uncommented to set the date and time
//  rtc.setDOW(MONDAY);     // Set Day-of-Week to SUNDAY
//  rtc.setTime(15, 51, 0);     // Set the time to 12:00:00 (24hr format)
//  rtc.setDate(9, 11, 2017);   // Set the date to January 1st, 2014
}

void loop()
{
  int hour = rtc.getTime().hour;
  int min = rtc.getTime().min;

    // Send time
  Serial.print(hour);
  Serial.print(":");
  Serial.print(min);
  Serial.println(" ");

  if(hour == 10 && min == 38) {
    active = true;
  }

  blinker();
}

void blinker() {
  while(active == true) {
    digitalWrite(12, HIGH);   // turn the LED on (HIGH is the voltage level)
    delay(1000);                       // wait for a second
    digitalWrite(12, LOW);    // turn the LED off by making the voltage LOW
    delay(1000);  
    buttonCheck();
  }
}

void buttonCheck() {
  if(digitalRead(11) == 1) {
    Serial.println("Button pushed");
    active = false;
  }
}

person Alex Foxleigh    schedule 13.09.2017    source источник
comment
Мой первый вопрос: какую схему вы используете для своей кнопки? Использует ли он резистор PULL UP или PULL DOWN или нет?   -  person svtag    schedule 13.09.2017
comment
Также стоит подумать о том, чтобы использовать прерывание для таймера и переводить Arduino в спящий режим в остальное время.   -  person Danny_ds    schedule 14.09.2017
comment
@sma Я новичок в электронике, и я не осознавал, что будет полезно использовать резистор с микроконтроллером, чтобы в цепи не было резистора. Это просто Arduino Nano, контроллер DS3231 RTC, белый светодиод и кнопка.   -  person Alex Foxleigh    schedule 14.09.2017
comment
@Danny_ds не уверен, что это значит, поэтому я погуглю, спасибо:   -  person Alex Foxleigh    schedule 14.09.2017
comment
@Danny_ds ах! Это может сработать, но это означает, что мне придется найти другое средство, чтобы заставить свет мигать. Может быть, я могу сделать это с конденсатором.   -  person Alex Foxleigh    schedule 14.09.2017
comment
@Sma переключил контакт 11 на INPUT_PULLUP и изменил код, чтобы проверить, что это сработало как шарм. Спасибо :)   -  person Alex Foxleigh    schedule 14.09.2017


Ответы (1)


Ответ спасибо @sma + небольшая настройка кода, в основном я переключил контакт 11 с INPUT на INPUT_PULLUP и переработал код, чтобы перехватить это

#include <DS3231.h>

// Init the DS3231 using the hardware interface
DS3231  rtc(SDA, SCL);
bool active = false;

void setup()
{
  // Setup Serial connection
  Serial.begin(115200);
  // Uncomment the next line if you are using an Arduino Leonardo
  //while (!Serial) {}

  // Initialize the rtc object
  rtc.begin();
  pinMode(12, OUTPUT);
  pinMode(11, INPUT_PULLUP);
  // The following lines can be uncommented to set the date and time
//  rtc.setDOW(MONDAY);     // Set Day-of-Week to SUNDAY
//  rtc.setTime(15, 51, 0);     // Set the time to 12:00:00 (24hr format)
//  rtc.setDate(9, 11, 2017);   // Set the date to January 1st, 2014
}


int blinker(int state = 1) {
  if(state == 1) {
    if (active == true) {
      digitalWrite(12, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);              // wait for a second
      digitalWrite(12, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);  
      buttonCheck();
    }
  }
}

int buttonCheck() {
  Serial.println(digitalRead(11));
  if(digitalRead(11) == 0) {
    Serial.println("Button pushed");
    active = false;
    blinker(0);
  }
}


void loop()
{
  int hour = rtc.getTime().hour;
  int min = rtc.getTime().min;

  // Send time
  Serial.print(hour);
  Serial.print(":");
  Serial.print(min);
  Serial.println(" ");
  Serial.println(digitalRead(11));

  if(hour == 9 && min == 59) {
    active = true;
  }

  blinker();
  delay(1000); 
}
person Alex Foxleigh    schedule 14.09.2017
comment
Подробнее об этом можно прочитать здесь, почему это происходит и о его преимуществах. - person svtag; 14.09.2017