Course Content
코딩소스
0/1
[아두이노 키트] 조이스틱모듈
About Lesson

기본설정

  1. 아두이노 설치 및 환경설정이 완료된 상태여야 합니다.

2. 라이브러리는 하기 버튼을 눌러 다운로드하고 설치하세요

3. 아래 소스코드를 보드설정-컴파일-업로드 과정을 진행 후 실행하세요

소스 코드

– 코드설명 :

  • 조이스틱을 상하좌우로 움직이거나 눌렀을 때,  LCD와 시리얼 모니터에 현재 방향과 버튼 상태를 실시간으로 표시합니다.
  • LCD 표시
    – 첫 줄에는 현재 방향(LEFT, RIGHT, UP, DOWN, CENTER) 표시
    – 두 번째 줄에는 방향에 따라 각각의 화살표 또는 문자 표시
    – 추가로 displayDirectionInfo() 함수를 사용하면 각 방향에 따라 LCD에 다른 화면 효과 표시 가능
  • 버튼 감지
    – 조이스틱을 누르면 스위치 값이 LOW로 감지됩니다.
    – 버튼 상태도 LCD와 시리얼 모니터에 “PRESSED” 또는 “RELEASED”로 표시됩니다.
  • 시리얼 모니터 출력
    – X축, Y축 값, 방향, 버튼 상태를 시리얼 모니터에 실시간으로 출력합니다.
				
					#include <Wire.h>
#include <LiquidCrystal_I2C.h>

// I2C LCD 설정 (주소: 0x27, 16x2 크기)
LiquidCrystal_I2C lcd(0x27, 16, 2);

// 조이스틱 핀 설정
const int joystickX = A0;// X축 (좌우)
const int joystickY = A1;// Y축 (상하)
const int joystickSW = 5;// 스위치 (누름)

// 임계값 설정
const int threshold = 100;// 민감도 조절
const int centerValue = 512; // 중앙값

void setup() {
// I2C LCD 초기화
lcd.begin();
lcd.backlight();

// 조이스틱 스위치 핀 설정
pinMode(joystickSW, INPUT_PULLUP);

// 시리얼 통신 시작
Serial.begin(9600);

// 초기 화면
lcd.setCursor(0, 0);
lcd.print("Joystick Test");
lcd.setCursor(0, 1);
lcd.print("Direction:");
delay(2000);

// 화면 클리어
lcd.clear();
}

void loop() {
// 조이스틱 값 읽기
int xValue = analogRead(joystickX);
int yValue = analogRead(joystickY);
int switchValue = digitalRead(joystickSW);

// 방향 판단
String direction = "";
String arrow = "";

// X축 (좌우) 판단
if (xValue < centerValue - threshold) {
direction = "LEFT";
arrow = "<--";
} else if (xValue > centerValue + threshold) {
direction = "RIGHT"; 
arrow = "-->";
}
// Y축 (상하) 판단 
else if (yValue < centerValue - threshold) {
direction = "UP";
arrow = " ^ ";
} else if (yValue > centerValue + threshold) {
direction = "DOWN";
arrow = " v ";
} else {
direction = "CENTER";
arrow = " o ";
}

// 스위치 상태 확인
String switchStatus = "";
if (switchValue == LOW) {
switchStatus = " PRESSED";
}

// LCD에 표시
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Dir: " + direction);
lcd.setCursor(0, 1);
lcd.print(arrow + switchStatus);

// 시리얼 모니터에도 출력
Serial.print("X: ");
Serial.print(xValue);
Serial.print(" Y: ");
Serial.print(yValue);
Serial.print(" Direction: ");
Serial.print(direction);
Serial.print(" Switch: ");
Serial.println(switchValue == LOW ? "PRESSED" : "RELEASED");
delay(200); // 업데이트 간격
}

// 추가 기능: 방향별 다른 화면 표시
void displayDirectionInfo(String dir) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Moving: " + dir);

if (dir == "LEFT") {
lcd.setCursor(0, 1);
lcd.print("<<<<<<<<<<<<");
} else if (dir == "RIGHT") {
lcd.setCursor(0, 1);
lcd.print(">>>>>>>>>>>>");
} else if (dir == "UP") {
lcd.setCursor(0, 1);
lcd.print("^^^^^^^^^^^^");
} else if (dir == "DOWN") {
lcd.setCursor(0, 1);
lcd.print("vvvvvvvvvvvv");
} else {
lcd.setCursor(0, 1);
lcd.print("-- CENTER --");
}
}
				
			

작동영상