[pre lang="arduino" line="1" file="joystick_controller.ino"]// 模拟
const byte PIN_ANALOG_X = A0;
const byte PIN_ANALOG_Y = A1;
// 数字
const byte PIN_ANALOG_K = 0;
// X中轴,区间值 [515..518]
const int X_THRESHOLD_LOW = 515;
const int X_THRESHOLD_HIGH = 518;
// Y中轴,区间值 [518..520]
const int Y_THRESHOLD_LOW = 518;
const int Y_THRESHOLD_HIGH = 520;
// 坐标
int x_position;
int y_position;
// 方向
int x_direction;
int y_direction;
// 按钮
boolean k_pressed = false;
void setup() {
Serial.begin(9600);
pinMode(PIN_ANALOG_K, INPUT); // 摇杆,中间开关
}
void loop () {
toggleBtn(PIN_ANALOG_K);
if(k_pressed){
setDirection(PIN_ANALOG_X, PIN_ANALOG_Y);
getDirection(x_direction, y_direction);
}
}
void setDirection(byte x, byte y){
x_position = analogRead(x);
y_position = analogRead(y);
// 默认方向,中间
x_direction = 0;
y_direction = 0;
// 判定,横轴方向
if (x_position > X_THRESHOLD_HIGH) {
x_direction = 1; // 右
}else if (x_position < X_THRESHOLD_LOW) {
x_direction = 2; // 左
}
// 判定,竖轴方向
if (y_position > Y_THRESHOLD_HIGH) {
y_direction = 3; // 上
}else if (y_position < Y_THRESHOLD_LOW) {
y_direction = 6; // 下
}
}
void getDirection(int x, int y){
int direct = y;
if (x != 0){ // 判定,X轴方向叠加
direct = x + y;
}
switch (direct){
case 0: // 横/竖,中间
break;
case 1: // 右
Serial.println("R");
debug();
break;
case 2: // 左
Serial.println("L");
debug();
break;
case 3: // 上
Serial.println("U");
debug();
break;
case 4: // 右上
Serial.println("RU");
debug();
break;
case 5: // 左上
Serial.println("LU");
debug();
break;
case 6: // 下
Serial.println("D");
debug();
break;
case 7: // 右下
Serial.println("RD");
debug();
break;
case 8: // 左下
Serial.println("LD");
debug();
break;
}
}
void debug(){
Serial.println(" //========================= ");
Serial.print(" X: ");
Serial.print(x_direction, DEC);
Serial.print(" Y: ");
Serial.print(y_direction, DEC);
Serial.println(" //==== ");
}
void toggleBtn(byte k){ // 开关
int state = digitalRead(k);
if(state == 0){
if(k_pressed){
k_pressed = false;
Serial.println(" CLOSE ");
}else{
k_pressed = true;
Serial.println(" OPEN ");
}
delay(200);
}
}[/code] |