/*
1층 각도를 180
2층 각도를 90
3층 각도를 0 으로 하겠습니다.
*/
/*
리팩토링 요소들
1. 버튼 핀 번호를 배열로 만들어서 for문으로 처리( 보류 )
2. 층 수를 배열로 만들어서 for문으로 처리 ( 보류 )
3. 코드 주석 다시 정리
4. 버튼의 디바운스 처리 ( 없는 가정하에 보류 )
5. 각 층 버튼 처리 의 비슷한 부분을 함수로 묶어서 처리( 완료 )
6. 시리얼 출력문 정리 ( 보류 )
7. 서보모터 연결 및 해제를 State Machine으로 처리 ( 보류 )
8. 시스템 시작시 층을 1층으로 초기화 하지 말고 현재 층을 읽을 수 있는 코드로 변경을 생각 해볼 것( 보류 )
9. 변수 이름 수정 (F -> floor_difference) ( 완료 )
10. delay()를 사용하지 않고 millis()를 사용해서 시간을 계산해서 처리( 보류 )
11. loop() 함수를 작게 만들기 위해서 함수로 분리 , 예를 들어 void check_button() , void move_elevator() 등등 ( 완료 )
12. if(current_floor < target_floor) -> if(target_floor > current_floor) 로 변경
*/
#include <Servo.h>
Servo servo;
// 현재 층 과 목표 층 변수(고정)
int current_floor = 1;
int target_floor = 1;
int floor_difference;
// 버튼 핀 번호
const int FIRST_FLOOR_BUTTON_PIN = 2;
const int SECOND_FLOOR_BUTTON_PIN = 3;
const int THIRD_FLOOR_BUTTON_PIN = 4;
void setup()
{
Serial.begin(9600);
servo.attach(9);
servo.write(180);
pinMode(FIRST_FLOOR_BUTTON_PIN, INPUT_PULLUP);
pinMode(SECOND_FLOOR_BUTTON_PIN, INPUT_PULLUP);
pinMode(THIRD_FLOOR_BUTTON_PIN, INPUT_PULLUP);
}
void loop()
{
// 버튼을 누르면 목표 층을 변경 합니다.
checkButton();
// 현재 층과 목표 층이 다르면 엘리베이터를 이동 시킵니다.
if (current_floor != target_floor)
{
move(target_floor);
}
Serial.print("C_floor: ");
Serial.print(current_floor);
Serial.print(" T_floor: ");
Serial.print(target_floor);
Serial.print(" Btn 1: ");
Serial.print(digitalRead(FIRST_FLOOR_BUTTON_PIN));
Serial.print(" Btn 2: ");
Serial.print(digitalRead(SECOND_FLOOR_BUTTON_PIN));
Serial.print(" Btn 3: ");
Serial.println(digitalRead(THIRD_FLOOR_BUTTON_PIN));
}
// 엘리베이터 부분 별도 함수로 처리
void move(int target_floor)
{
// 현재 위치 층과 목표 층의 차이를 계산합니다.
floor_difference = abs(target_floor - current_floor);
servo.attach(9);
// 서보모터를 회전 시킵니다.
if (target_floor == 1)
{
servo.write(180);
}
else if (target_floor == 2)
{
servo.write(90);
}
else if (target_floor == 3)
{
servo.write(0);
}
delay(1000 * floor_difference); // 층 수 차이 * 1초 곱한 시간만큼 대기
current_floor = target_floor;
}
// 버튼 부분 별도 함수로 처리 , 디바운스가 없는 가정하에
void checkButton()
{
// 각 층의 버튼 핀의 상태를 확인 합니다.
if(digitalRead(FIRST_FLOOR_BUTTON_PIN) == LOW)
{
target_floor = 1;
}
else if(digitalRead(SECOND_FLOOR_BUTTON_PIN) == LOW)
{
target_floor = 2;
}
else if(digitalRead(THIRD_FLOOR_BUTTON_PIN) == LOW)
{
target_floor = 3;
}
}