优化Arduino本规范

时间:2014-09-02 06:04:01

标签: arduino

我装了一个光传感器,所以当外面漆黑时,它会打开灯。 所以我现在连接了Photo Sensitive传感器和一个校准按钮。 我想知道你是否有任何提示如何优化这个巨大的代码...... 我确定那里有因为我是Arduino的新人。

#include <LiquidCrystal.h>

const int RED_Pin = 9;
const int GREEN_Pin = 10;
const int BLUE_Pin = 11;
const int PHOTO_sense = 0;
const int Button = 12;
int RoomLight;
int Sensor;

LiquidCrystal lcd(7,6,5,4,3,2);

void setup()
{


  lcd.begin(16,2);
  lcd.clear();
 pinMode(RED_Pin,OUTPUT);
 pinMode(GREEN_Pin,OUTPUT);
 pinMode(BLUE_Pin,OUTPUT); 
 pinMode(Button,INPUT);
 Serial.begin(9600);
 sync();
 Serial.print(Button);
}


void loop(){
  Sensor = analogRead(PHOTO_sense);
  Sensor = map(Sensor,0,1023,0,255);
  Sensor = constrain(Sensor,0,255);
  if(Sensor < RoomLight-5){
   digitalWrite(RED_Pin,LOW);
   digitalWrite(GREEN_Pin,HIGH);
  }else{
   digitalWrite(GREEN_Pin,LOW);
   digitalWrite(RED_Pin,HIGH);
  }
  delay(500);
  if(digitalRead(Button)==0){ //Buton Is Pressed so We Need to Sync
    delay(2000);
      if(digitalRead(Button) == 0){
          sync();
      }
    delay(2500);
  }
}

int sync(){
  lcd.clear();
  lcd.print("Calibriting");
  int compre [4];
  int Sum=0;
  for (int Loop = 4;Loop>0;Loop--){
  lcd.print(".");
  delay(500);
  digitalWrite(BLUE_Pin,HIGH);
  compre[Loop] =  analogRead(PHOTO_sense);
  delay(500); 
  digitalWrite(BLUE_Pin,LOW);

  Sum=Sum+compre[Loop];
  }
    RoomLight = Sum/4;    
    RoomLight = map(RoomLight,0,1023,0,255);
    RoomLight = constrain(RoomLight,0,255);    
    lcd.clear();

    lcd.print("done Calibration");
    delay(2500);
 return 0; 
}

1 个答案:

答案 0 :(得分:0)

快速浏览第一个建议可以是:

添加一个重复工作的功能

我在同一个动作中至少看到你两次

Sensor = map(Sensor,0,1023,0,255);
Sensor = constrain(Sensor,0,255);
RoomLight = map(RoomLight,0,1023,0,255);
RoomLight = constrain(RoomLight,0,255); 

你可以添加这样的功能

int recalc_light(input)
{
    retVal = map(input, 0, 1023, 0, 255);
    return constrain(retVal, 0, 255);
}

然后以这种方式调用它:

Sensor = recalc_light(analogRead(PHOTO_sense));
RoomLight = recalc_light(Sum/4);

其次我看到你的函数int sync()总是返回0

你可以随时重写它:

void sync()
{
    lcd.clear();
    ...
    ...
    lcd.print("done Calibration");
    delay(2500);
}

第三条评论可能是一致地写,例如总是在新线上开始{或}。为了清晰的概述(但这是个人风格),你可以像我上面所做的那样确保它是一行中唯一的角色。 在每个&#39; {&#39;之后,还要记住身份。添加一些额外的2或4个空格。

通过这种方式,您的代码看起来会更好。

通过示例:

void sync()
{
     lcd.clear();
     lcd.print("Calibriting");
     int compre [4];
     int Sum=0;
     for (int Loop = 4;Loop>0;Loop--)
     {
          lcd.print(".");
          delay(500);
          digitalWrite(BLUE_Pin,HIGH);
          compre[Loop] =  analogRead(PHOTO_sense);
          delay(500);
          digitalWrite(BLUE_Pin,LOW);
          Sum=Sum+compre[Loop];
     }
     RoomLight = recalc_light(Sum/4);    
     lcd.clear();
     lcd.print("done Calibration");
     delay(2500); 

}