dimanche 8 octobre 2017

Global Variable edited in 'if' and reset back to initial in 'else if'

I'm new to programming my Arduino, and I'm attempting to be able to manually set a clock. I'm using a rotary sensor to select the hours and then a button to confirm the hours and swap to change the minutes. However, currently, when I go through changing the hours and select the appropriate minute value, the hour value is reset back to 00.

I am using a Genuino Uno board, with Grove rotary sensor, LCD display and button, as well as the base shield.

I'm hoping someone can clarify my error and suggest why my variables are resetting between the editing the hours and the minutes.

#include <rgb_lcd.h>

rgb_lcd lcd;

const int colorR = 255;
const int colorG = 20;
const int colorB = 147;

const int analogInPin = 0;  // Analog input pin that the rotary sensor is attached to

int sensorValue = 0;        // value read from the rotary sensor
int outputValue = 0;
int button = 2;
int hour = 00;
int minute = 00;
int button_state = 0;
int minute_temp = 0;
int hour_temp = 0;

void setup() {
  // set up the LCD's number of columns and rows:
  Serial.begin(9600);
  lcd.begin(16, 2);
  pinMode(button, INPUT);

  lcd.setRGB(colorR, colorG, colorB);
  Serial.println("HELLO");

}
void loop() {
  int confirm = 0;
  confirm = digitalRead(button);
  if (button_state == 0) {
    // read the analog in value:
    sensorValue = analogRead(analogInPin);
    // map it to the range of the analog out:
    outputValue = map(sensorValue, 0, 1023, 0, 23);
    // change the analog out value:
    lcd.clear();
    lcd.setCursor(0, 0);

    String hour = String(outputValue);
    if (outputValue < 10) {
      hour = ("0" + hour);
    }

    minute_temp = minute;
    String minute = String(minute_temp);
    if (minute_temp < 10) {
      minute = ("0" + minute);
    }

    lcd.print(hour);
    lcd.print(":");
    lcd.print(minute);

    // wait 10 milliseconds before the next loop
    // for the analog-to-digital converter to settle
    // after the last reading:
    delay(10);
    if (confirm == HIGH){
      button_state = 1;
      delay(1000);
    }
  }
  else if (button_state == 1){
    // read the analog in value:
    sensorValue = analogRead(analogInPin);
    // map it to the range of the analog out:
    outputValue = map(sensorValue, 0, 1023, 0, 59);
    // change the analog out value:
    lcd.clear();
    lcd.setCursor(0, 0);

    String minute = String(outputValue);
    if (outputValue < 10) {
      minute = ("0" + minute);
    }

    hour_temp = hour;
    String hour = String(hour_temp);
    if (hour_temp < 10) {
      hour = ("0" + hour);
    }

    lcd.print(hour);
    lcd.print(":");
    lcd.print(minute);

    // wait 10 milliseconds before the next loop
    // for the analog-to-digital converter to settle
    // after the last reading:
    delay(10);
    if (confirm == HIGH){
      button_state = 5;
    }
  }
}

Thanks very much.

Aucun commentaire:

Enregistrer un commentaire