BASIC4MCU | 질문게시판 | 스위치를 누를때마다 다르게 작동시키려면 어떻게하죠?
페이지 정보
작성자 공부하자 작성일2021-04-04 18:01 조회2,936회 댓글1건본문
스위치를 한번 누르면 led가 5v로 켜지고 한번 더 누르면 2.5v로 켜지고 한번 더 누르면 꺼지는걸 반복되게 하고싶은데
어떻게 짜야하나요?
이렇게 하는게 맞을까요?
int buttonPin = 2;
int ledPin = 9;
int state = 0;
int count = 0;
int buttonState = 0;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
}
void loop() {
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH) {
if (state == 0) {
delay(10);
state = 1;
}
}
if (buttonState == LOW) {
if(state == 1){
count += 1;
delay(10);
state = 0;
}
}
if(count%3 == 1) {
digitalWrite(ledPin, HIGH);
if(count%3 == 2) {
analogWrite(ledPin, 127);
if(count%3 == 0) {
digitalWrite(ledPin, LOW);
}
}
}
}
댓글 1
조회수 2,936master님의 댓글
master 작성일
int buttonPin=2,ledPin= 9;
//
int state=0,count=0;
//
void setup(){}
//
void loop(){
if(digitalRead(buttonPin)==0){
if(state==0){ delay(100); state=1;
if(++count>2)count=0;
if(count==1)analogWrite(ledPin,255);
if(count==2)analogWrite(ledPin,127);
if(count==0)analogWrite(ledPin,0);
}
}
else{
if(state==1){ delay(100); state=0; }
}
}