首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在按下按钮时运行循环

在按下按钮时运行循环
EN

Stack Overflow用户
提问于 2016-08-04 13:41:04
回答 1查看 203关注 0票数 0

每当我按下键盘上的'0‘时,我需要帮助为线路跟踪器循环几个语句,并让它继续循环,直到按钮再次被按下,然后它又回到运行主循环。任何帮助都是非常欢迎的。

代码语言:javascript
复制
#include <LiquidCrystal.h>
#include <Time.h>
#include <Wire.h>
#include <DS1307RTC.h>
#include <Servo.h>
#include <Keypad.h>

//Pins of LCD     RS  E  D4 D5  D6 D7
LiquidCrystal lcd(12, 11, 10, 9, 8, 7); // Pins of Arduino
Servo servoMain; // Define our Servo
int tempPin = A0; //LM35 Pin
int ldrPin = A1;  //LDR Pin
int led = 6;    //LED Pin
int buzzer = 13;
float temp;
float tempC;
int lightReading;
int numTones = 2;
int tones[] = {440, 349};
int Tones = 3;
int ones2[] = {988, 740, 988};
int bulb = A2;
int val;
int motor1Pin1 = 26; // pin 2 on L293D IC
int motor1Pin2 = 25; // pin 7 on L293D IC
int enable1Pin = 27; // pin 1 on L293D IC
int motor2Pin1 = 23; // pin 10 on L293D IC
int motor2Pin2 = 22; // pin 15 on L293D IC
int enable2Pin = 24; // pin 9 on L293D IC
int state;
int flag = 0;      //makes sure that the serial only prints once the state
int stateStop = 0;
int s1val;
int s2val;
int led1 = 43;
int led2 = 42;
const byte ROWS = 4; // Four rows
const byte COLS = 3; // Three columns
// Define the Keymap
char keys[ROWS][COLS] = {
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};
// Connect keypad ROW0, ROW1, ROW2 and ROW3 to these Arduino pins.
byte rowPins[ROWS] = {48, 53, 52, 50};
// Connect keypad COL0, COL1 and COL2 to these Arduino pins.
byte colPins[COLS] = {49, 47, 51 };

// Create the Keypad
Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup()
{
  lcd.begin(16, 2);
  pinMode(led, OUTPUT);
  pinMode(tempPin, INPUT);
  pinMode(ldrPin, INPUT);
  pinMode(buzzer, OUTPUT);
  pinMode(bulb, OUTPUT);
  pinMode(motor1Pin1, OUTPUT);
  pinMode(motor1Pin2, OUTPUT);
  pinMode(enable1Pin, OUTPUT);
  pinMode(motor2Pin1, OUTPUT);
  pinMode(motor2Pin2, OUTPUT);
  pinMode(enable2Pin, OUTPUT);
  digitalWrite(enable1Pin, HIGH); // set to high so that motor can run
  digitalWrite(enable2Pin, HIGH); // set to high so that motor can run
  servoMain.attach(3); // servo on pin 3
  servoMain.write(72);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  kpd.addEventListener(keypadEvent);
  Serial.begin(9600);

  setSyncProvider(RTC.get);   // the function to get the time from the RTC
  if (timeStatus() != timeSet)
    Serial.println("Unable to sync with the RTC");
  else
    Serial.println("RTC has set the system time");

  lcd.clear();
  beep(100);
}
void loop()
{
  tempC = (5.0 * analogRead(tempPin) * 100.0) / 1024;
  temp = tempC;
  lightReading = analogRead(ldrPin);
  val = analogRead(3);
  Serial.println(val);
  digitalClockDisplay();
  s1val = analogRead(6);
  s2val = analogRead(7);
  char key = kpd.getKey();

  if (Serial.available() > 0)
  {
    state = Serial.read();
    flag = 0;
  }

  if (val >= 700)             // check if the input is HIGH
  {
    val = analogRead(3);
    doSomething('f');
    delay(1000);
    if (val >= 700)
    {
      doSomething('g');
    }

    else
    {
      doSomething('m');
    }
  }

  else
  {
    doSomething('m');
  }

  if (temp >= 35 && temp < 50) // "Hot Warning" temp
  {
    doSomething('a');
  }

  else if (temp >= 34 && temp < 35) // "Warm Warning" temp
  {
    doSomething('b');
  }

  else if (temp >= 50) // "Danger Warning" temp
  {
doSomething('c');
  }

  else
  {
    doSomething('m');
  }

  if (lightReading > 100 && lightReading <= 200) // Dim Warning
  {
    doSomething('d');
  }

  else if (lightReading <= 100) // Dark Warning
  {
    doSomething('e');
  }

  else
  {
    doSomething('m');
  }

  if (state == '1') //Motor
  {
    doSomething('h');
  }

  else if ( state == '2')//Motor
  {
    doSomething('i');
  }

  else if ( state == '3')//Motor
  {
    doSomething('j');
  }

  else if ( state == '4') //Motor
  {
    doSomething('k');
  }

  else if ( state == '5')//Motor
  {
    doSomething('l');
  }

  else
  {
    doSomething('m');
  }

  if (key) // Check for a valid key.
  {
    switch (key)
    {
  case '1':

    Serial.println(key);
    servoMain.write(72);  // Turn Servo to 0
    break;

  case '2':

    Serial.println(key);
    servoMain.write(0);  // Turn Servo Left to 36 degrees
    break;

  case '3':

    Serial.println(key);
    servoMain.write(36);   // Turn Servo Left to 72 degrees
    break;

  case '4':

    Serial.println(key);
    servoMain.write(108);  // Turn Servo left to 108 degrees
    break;

  case '5':

    Serial.println(key);
    servoMain.write(144); // Turn Servo left to 144 degrees
    break;

  case '6':

    Serial.println(key);
    break;

  case '7':

    Serial.println(key);
    break;

  case '8':

    Serial.println(key);
    break;

  case '9':

    Serial.println(key);
    break;

  case '0':

    Serial.println(key);
    break;

  case '*':

    Serial.println(key);
    break;

  case '#':

    Serial.println(key);
    break;
    }
  }

  delay(300);
  lcd.clear();
  Serial.print("Light,"); Serial.print(lightReading); Serial.print(" "); Serial.print('\n');
}

void keypadEvent(KeypadEvent key) {
  switch (kpd.getState()) {

    //U can use three modes: PRESSED, HOLD or RELEASED.
    //U can also add more than one event with more than one key.
    case PRESSED:
      if (key == '0') {
        if (s1val <= 0 && s2val >= 2) //turn left
        {
          digitalWrite(motor1Pin1, HIGH);
          digitalWrite(motor1Pin2, LOW);
          digitalWrite(motor2Pin1, LOW);
          digitalWrite(motor2Pin2, LOW);
          digitalWrite(led2, HIGH);
          digitalWrite(led1, LOW);
        }

        else if (s1val >= 2  && s2val <= 0) // turn right
        {
          digitalWrite(motor1Pin1, LOW);
          digitalWrite(motor1Pin2, LOW);
          digitalWrite(motor2Pin1, LOW);
          digitalWrite(motor2Pin2, HIGH);
          digitalWrite(led1, HIGH);
          digitalWrite(led2, LOW);
        }

        else if (s1val >= 2 && s2val >= 2) // go forward
        {
          digitalWrite(motor1Pin1, HIGH);
          digitalWrite(motor1Pin2, LOW);
          digitalWrite(motor2Pin1, LOW);
          digitalWrite(motor2Pin2, HIGH);
          digitalWrite(led2, HIGH);
          digitalWrite(led1, HIGH);
        }

        else // stop
        {
          digitalWrite(motor1Pin1, LOW);
          digitalWrite(motor1Pin2, LOW);
          digitalWrite(motor2Pin1, LOW);
          digitalWrite(motor2Pin2, LOW);
          digitalWrite(led1, LOW);
          digitalWrite(led2, LOW);
        }
      }
  }
}

void doSomething(char condition) {
  switch (condition) {
  case 'a' :  // if temp is higher than 35°C
  lcd.setCursor(0, 0);
  lcd.print("   Room Hot!!   ");
  digitalWrite(led, HIGH);
  delay(200);
  beep(150);
  digitalWrite(led, LOW);
  delay(200);
  break;

case 'b' :  // if temp is higher than 30°C
  lcd.setCursor(0, 0);
  lcd.print("   Room Warm!   ");
  digitalWrite(led, HIGH);
  delay(200);
  beep(150);
  digitalWrite(led, LOW);
  delay(200);
  break;

case 'c' :  // if temp is higher than 50°C
  lcd.setCursor(0, 0);
  lcd.print("    Warning     ");
  lcd.setCursor(0, 1);
  lcd.print("    Danger!!    ");
  digitalWrite(led, HIGH);
  delay(200);
  beep2(150);
  digitalWrite(led, LOW);
  delay(200);
  break;

case 'd' : // if room is dim
  analogWrite(bulb, 150);
  lcd.setCursor(0, 1);
  lcd.print("   Room Dim!!   ");
  digitalWrite(led, HIGH);
  delay(200);
  beep(150);
  digitalWrite(led, LOW);
  delay(200);
  break;

case 'e': // if room is dark
  analogWrite(bulb, 255);
  lcd.setCursor(0, 1);
  lcd.print("   Room Dark    ");
  digitalWrite(led, HIGH);
  delay(200);
  beep(150);
  digitalWrite(led, LOW);
  delay(200);
  break;

case 'f': //  when motion detected by I.R Sensor
  analogWrite(bulb, 0);
  lcd.setCursor(0, 0);
  lcd.print("Motion Detected");
  digitalWrite(motor1Pin1, LOW);
  digitalWrite(motor1Pin2, LOW);
  digitalWrite(motor2Pin1, LOW);
  digitalWrite(motor2Pin2, LOW);
  delay(1000);
  break;

case 'g':                  //motion detected turn on light for 20secs
  analogWrite(bulb, 255);
  delay(5000);
  break;

case 'h':                        // forward
  digitalWrite(motor1Pin1, HIGH);
  digitalWrite(motor1Pin2, LOW);
  digitalWrite(motor2Pin1, LOW);
  digitalWrite(motor2Pin2, HIGH);
  break;

case 'i':                        //left
  digitalWrite(motor1Pin1, HIGH);
  digitalWrite(motor1Pin2, LOW);
  digitalWrite(motor2Pin1, LOW);
  digitalWrite(motor2Pin2, LOW);
  break;

case 'j':                        //stop
  digitalWrite(motor1Pin1, LOW);
  digitalWrite(motor1Pin2, LOW);
  digitalWrite(motor2Pin1, LOW);
  digitalWrite(motor2Pin2, LOW);
  break;

case 'k':                        //right
  digitalWrite(motor1Pin1, LOW);
  digitalWrite(motor1Pin2, LOW);
  digitalWrite(motor2Pin1, LOW);
  digitalWrite(motor2Pin2, HIGH);
  break;

case 'l':                        //reverse
  digitalWrite(motor1Pin1, LOW);
  digitalWrite(motor1Pin2, HIGH);
  digitalWrite(motor2Pin1, HIGH);
  digitalWrite(motor2Pin2, LOW);
  break;

default:
  lcd.setCursor(0, 0);
  lcd.print("Time:");
  lcd.setCursor(6, 0);                                            // Set LCD cursor position (column, row)
  lcd.print(hour());
  lcd.print(":");
  lcd.print (minute());
  lcd.print(" ");
  lcd.print(second());
  lcd.print("     ");
  lcd.setCursor(0, 1);
  lcd.print("Date:");
  lcd.setCursor(6, 1);                                           // Set LCD cursor position (column,row)
  lcd.print(day());
  lcd.print(".");
  lcd.print(month());
  lcd.print(".");
  lcd.print(year());
  analogWrite(bulb, 0);
  break;

  }
}

void beep(unsigned char delayms) { // buzzeer tones for room hot and warm
  for (int x = 0; x < numTones; x++)
  {
    tone(buzzer, tones[x]);
    delay(delayms);
  }
  noTone(buzzer);
}
void beep2(unsigned char delayms2) { // buzzer tone for room above 50°C
  for (int y = 0; y < Tones; y++)
  {
   tone(buzzer, ones2[y]);
    delay(delayms2);
  }
  noTone(buzzer);
}

void digitalClockDisplay() {
  // digital clock display of the time
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print(" ");
  Serial.print(day());
  Serial.print(" ");
  Serial.print(month());
  Serial.print(" ");
  Serial.print(year());
  Serial.println();

  lcd.setCursor(0, 0);
  lcd.print("Time:");
  lcd.setCursor(6, 0);        // Set LCD cursor position (column, row)
  lcd.print(hour());
  lcd.print(":");
  lcd.print (minute());
  lcd.print(" ");
  lcd.print(second());
  lcd.print(" ");
  lcd.setCursor(0, 1);
  lcd.print("Date:");
  lcd.setCursor(6, 1);       // Set LCD cursor position (column,row)
  lcd.print(day());
  lcd.print(".");
  lcd.print(month());
  lcd.print(".");
  lcd.print(year());

  // Print text to LCD
  // Delay to read text
  // Clear the display

}

void printDigits(int digits) {
  // utility function for digital clock display: prints preceding colon and leading 0
  Serial.print(":");
  if (digits < 10)
  Serial.print('0');
  Serial.print(digits);
}
EN

回答 1

Stack Overflow用户

发布于 2016-08-04 16:14:21

如果您希望代码在按下按钮后继续执行某些操作,则需要一个“切换”变量,该变量在按下按钮后设置,在再次按下按钮时重置。

在全局声明中,可以在main()中放入bool mustDoIt = false;

代码语言:javascript
复制
if (keyPressed) {
  mustDoIt = !mustDoIt;
}

if (mustDoIt) {
  ...
}

我注意到相当多的事情:

对于temp,你有一个很大的if ... else (顺便说一句,这不是一个好名字,它的意思可能是temperaturetemporary),你可以在上面调用另一个函数,在里面进行同样的检查。为什么不把温度传递给函数并检查它的内部呢?

  • 你要重复几次代码,

考虑为此编写一个函数:

类似于:

代码语言:javascript
复制
void displayMessage(char *first_row, char *second_row) {
  lcd.setCursor(0, 0);
  lcd.print(first_row);
  lcd.setCursor(0, 1);
  lcd.print(second_row);
  digitalWrite(led, HIGH);
  delay(200);
  beep(150);
  digitalWrite(led, LOW);
  delay(200);
}

  • ,你基本上只检查tempstatelightReading,所以就像我说的,把检查移到你真正需要的地方。将这三个变量传递给doSomething并在其中执行检查。

如下所示:

代码语言:javascript
复制
void doSomething(float temp, int state, int lightReading) {
  if (temp >= 35 && temp < 50)
  {
    displayMessage("   Room Hot!!   ", "");
  } else if (temp >= 34 && temp < 35)
  {
    displayMessage("   Room Warm!   ", "");
  } else if (temp >= 50)
  {
    displayMessage("    Warning     ", "    Danger!!    ");
  } //...Add rest of the checks here

  switch (state) {
    case 1: //Motor
      digitalWrite(motor1Pin1, HIGH);
      digitalWrite(motor1Pin2, LOW);
      digitalWrite(motor2Pin1, LOW);
      digitalWrite(motor2Pin2, HIGH);
    break;
    case 2:
      digitalWrite(motor1Pin1, HIGH);
      digitalWrite(motor1Pin2, LOW);
      digitalWrite(motor2Pin1, LOW);
      digitalWrite(motor2Pin2, LOW);
    break;
  //...Add rest of the checks here
  }

lightReading也是如此。

此外,可以将digitalClockDisplay函数编写为:

代码语言:javascript
复制
void digitalClockDisplay() {
  char time_string[32];
  char date_string[32];

  memset(time_string, 0, 32);
  sprintf(time_string, "Time: %02d:%02d:%02d     ", hour(), minute(), second());
  memset(date_string, 0, 32);
  sprintf(date_string, "date: %02d.%02d.%02d     ", day(), month(), year());

  displayMessage(time_string, date_string);

  Serial.println(time_string);
}

我现在不能测试代码,但我希望这能给你一些想法。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38759247

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档