반응형

버튼을 여러개 만들기보다 하나의 버튼으로 다양한 동작을 해야하는 경우가 있을 수 있다.



연속으로 버튼을 눌렀을때 작동하는지 알아보자



회로도








코드


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
int sw=4;
 
int states=0;
int counts=0;
unsigned long cnt=0;
 
void setup()
{
  Serial.begin(9600);
  pinMode(sw, INPUT);
}
 
void loop()
{
 
  if (digitalRead(sw) && counts==0 && cnt==0)//디지털핀에서 신호를 받았을때 
  {
    cnt=millis();//현재시간
    counts++;//누른횟수
  }
  else if (millis() > cnt+500 && cnt>0)//0.5초안에 버튼을 누르지 않고 1번이상 눌럿을때 counts저장후 빠져나옴
  {
    states=counts;//누른횟수 저장
    counts=0;// 초기화
    cnt=0;
  }
  else if (digitalRead(sw) && millis() > cnt+200)//0.2초안에 한번더 눌리면 counts 증가 시간 조절하면 눌리고있는경우도 체크가 가능할것이다.
  {
    cnt=millis();//시간초기화
    counts++;//카운트증가
 
    if (counts >= 3)
    {
      counts=3;//3번이상이면 카운트3
    }
  }
 
  switch (states)
  {
    case 0:
    break;
    case 1:
      Serial.write('1');
      counts=0;//초기화
      states=0;
    break;
    case 2:
      Serial.write('2');
      counts=0;//초기화
      states=0;
    break;
    case 3:
      Serial.write('3');
      counts=0;//초기화
      states=0;
    break;
  }
}

cs





참고


https://m.blog.naver.com/PostView.nhn?blogId=redcrow&logNo=221650833999&proxyReferer=https:%2F%2Fwww.google.com%2F

반응형
  • 네이버 블러그 공유하기
  • 네이버 밴드에 공유하기
  • 페이스북 공유하기
  • 카카오스토리 공유하기