728x90
반응형
** 버튼 토글
const int LED = 3;
const int Btn = 7;
int ledState = 0;
int buttonState = 0;
int p_buttonState = 0;
void setup()
{
Serial.begin(9600);
pinMode(LED, OUTPUT);
pinMode(Btn, INPUT);
}
void loop()
{
int reading = digitalRead(Btn);
if (reading != p_buttonState)
{
buttonState = reading;
if(buttonState == HIGH)
{
ledState = !ledState;
}
}
digitalWrite(LED, ledState);
p_buttonState = reading;
}
const int LED = 3;
const int Btn = 7;
int flag1 = 0;
int flag2 = 0;
int state = 0;
void setup()
{
pinMode(LED, OUTPUT);
pinMode(Btn, INPUT);
}
void loop()
{
flag1 = digitalRead(Btn);
if((flag1 == HIGH) && (flag2 == LOW))
{
state = !state;
delay(10);
}
flag2 = flag1;
if (state == 1)
{
digitalWrite(LED, HIGH);
}
else
{
digitalWrite(LED, LOW);
}
}
** millis() 함수를 활용한 LED 점멸
const int LED = 3;
const int Btn = 7;
int ledState = 0;
unsigned long interval = 1000;
unsigned long previousMillis = 0;
void setup()
{
Serial.begin(9600);
pinMode(LED, OUTPUT);
pinMode(Btn, INPUT);
}
void loop()
{
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > interval)
{
previousMillis = currentMillis;
if(ledState == LOW)
{
ledState = HIGH;
}
else
{
ledState = LOW;
}
digitalWrite(LED, ledState);
}
}
** 버튼 누른 시간에 따른 동작 소스 코드 (Button: pull-down)
/* LED */
const int LED = 3;
/* Button */
const int Btn = 7;
const int button_interval = 5000; // 5Sec.
long button_pressed_millis;
/* Time */
long current_millis;
bool isActive = false;
const int check_interval = 100;
void setup()
{
button_pressed_millis = 0;
pinMode(LED, OUTPUT);
pinMode(Btn, INPUT);
}
void loop()
{
current_millis = millis(); // record current time
if(digitalRead(Btn) == HIGH &&
current_millis - button_pressed_millis > button_interval)
{
button_pressed_millis = current_millis;
isActive = (isActive) ? false : true;
}
if(isActive)
{
digitalWrite(LED, HIGH);
}
else
{
digitalWrite(LED,LOW);
}
delay(check_interval);
}
728x90
반응형
'Firmware & Embedded > Components' 카테고리의 다른 글
Voltage step-up DC to DC Converter Module (XL6009E1) (0) | 2022.12.03 |
---|---|
Print Potentiometer Voltage and Resistance value. (0) | 2022.11.25 |
map() / constrain() function (0) | 2022.11.23 |
How to Program / Upload Code to ESP32-CAM AI-Thinker (Arduino IDE) (0) | 2022.11.23 |
LED Control (Button, Potentiometer) (0) | 2022.11.22 |