当我按下按钮(U),然后将其关闭时,我试图打开继电器5秒钟。然后打开第二个继电器10秒钟并关闭它。我想使用毫秒功能在不同的时间间隔控制8个继电器。 请更正我的代码。
为什么不起作用? (一个继电器编码)
#include <LiquidCrystal.h>
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
int ssr1 = 2;
int ssr2 = 3;
int lcd_key = 0;
int adc_key_in = 0;
#define R 0
#define U 1
#define D 2
#define L 3
#define S 4
#define N 5
unsigned long interval = 5000;
unsigned long previousMillis = 0;
int read_LCD_buttons(){
adc_key_in = analogRead(0);
if (adc_key_in > 1000) return N;
if (adc_key_in < 50) return R;
if (adc_key_in < 250) return U;
if (adc_key_in < 450) return D;
if (adc_key_in < 650) return L;
if (adc_key_in < 850) return S;
return N;
}
void setup(){
lcd.begin(16, 2);
lcd.setCursor(0,0);
lcd.print("Select:");
pinMode(3, OUTPUT);
}
void loop(){
unsigned long currentMillis = millis();
lcd.setCursor(0,1);
lcd_key = read_LCD_buttons();
switch (lcd_key){
case U:{
digitalWrite(3, HIGH);
if ((unsigned long)(currentMillis - previousMillis) >= interval){
digitalWrite(3, LOW);
previousMillis = millis();
}
lcd.print("START");
break;
}
case D:{
digitalWrite(3, LOW);
lcd.print("STOP");
break;
}
case N:{
break;
}
}
}
答案 0 :(得分:1)
我建议您查看各种Arduino教程。 但是,根据您的要求,我在下面提供了示例代码。 请注意,这尚未经过测试。但是,您应该了解逻辑并进行相应的调整。 还有许多其他方法可以达到相同的结果。
int relayState = RELAY_STATE_OFF; // track state of the relay
unsigned long relayOnAt = 0; // time at which relay was turned ON
void relay(int turnOn)
{
if( turnOn == ON ) digitalWrite(3,HIGH);
else digitalWrite(3,LOW);
}
void processRelay(int operateRelay)
{
switch(relayState){
case RELAY_STATE_OFF:
if( operateRelay == 1) {
relay(ON);
relayState = RELAY_STATE_ON;
relayOnAt = millis(); // remember when the relay was turned on
}
break;
case RELAY_STATE_ON: // wait here for interval seconds to elapse
if( millis() - relayOnAt >= interval) {
relay(OFF);
relayState = RELAY_STATE_OFF; // go back to checking key input
}
break;
default:
relayState = RELAY_STATE_OFF;
break;
}
}
int operateRelay = 0;
void loop(){
lcd.setCursor(0,1);
lcd_key = read_LCD_buttons();
operateRelay = 0;
if( lcd_key == U ) {
operateRelay = 1;
}
processRelay(operateRelay);
}