CODE 6.13 | 라인트레이서 자동차 만들기
| 01 | // 모터 제어 핀 설정 |
| 02 | int rightMotor1 = 5; |
| 03 | int rightMotor2 = 6; |
| 04 | int leftMotor1 = 9; |
| 05 | int leftMotor2 = 10; |
| 06 | |
| 07 | // 적외선 센서 핀 설정 (아날로그 핀 사용) |
| 08 | int leftSensor = A0; // 왼쪽 센서 |
| 09 | int rightSensor = A1; // 오른쪽 센서 |
| 10 | |
| 11 | // 검은색과 흰색을 구분하는 기준 숫자 설정 |
| 12 | int threshold = 500; |
| 13 | |
| 14 | void setup() { |
| 15 | // 모터 핀을 출력 모드로 설정 |
| 16 | pinMode(rightMotor1, OUTPUT); |
| 17 | pinMode(rightMotor2, OUTPUT); |
| 18 | pinMode(leftMotor1, OUTPUT); |
| 19 | pinMode(leftMotor2, OUTPUT); |
| 20 | } |
| 21 | |
| 22 | void loop() { |
| 23 | // 양쪽 센서 아날로그 값 읽기 |
| 24 | int leftValue = analogRead(leftSensor); |
| 25 | int rightValue = analogRead(rightSensor); |
| 26 | |
| 27 | // 1. 양쪽 모두 흰색일 때 (직진) |
| 28 | if (leftValue < threshold && rightValue < threshold) { |
| 29 | digitalWrite(rightMotor1, HIGH); |
| 30 | digitalWrite(rightMotor2, LOW); |
| 31 | digitalWrite(leftMotor1, HIGH); |
| 32 | digitalWrite(leftMotor2, LOW); |
| 33 | } |
| 34 | // 2. 왼쪽 센서만 검은 선을 밟았을 때 (좌회전하여 선 안으로 들어오기) |
| 35 | else if (leftValue >= threshold && rightValue < threshold) { |
| 36 | digitalWrite(rightMotor1, HIGH); |
| 37 | digitalWrite(rightMotor2, LOW); |
| 38 | digitalWrite(leftMotor1, LOW); |
| 39 | digitalWrite(leftMotor2, LOW); |
| 40 | } |
| 41 | // 3. 오른쪽 센서만 검은 선을 밟았을 때 (우회전하여 선 안으로 들어오기) |
| 42 | else if (leftValue < threshold && rightValue >= threshold) { |
| 43 | digitalWrite(rightMotor1, LOW); |
| 44 | digitalWrite(rightMotor2, LOW); |
| 45 | digitalWrite(leftMotor1, HIGH); |
| 46 | digitalWrite(leftMotor2, LOW); |
| 47 | } |
| 48 | // 4. 양쪽 모두 검은 선을 밟았을 때 (결승선 정지) |
| 49 | else { |
| 50 | digitalWrite(rightMotor1, LOW); |
| 51 | digitalWrite(rightMotor2, LOW); |
| 52 | digitalWrite(leftMotor1, LOW); |
| 53 | digitalWrite(leftMotor2, LOW); |
| 54 | } |
| 55 | } |
댓글 없음:
댓글 쓰기