极客工坊

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 11843|回复: 0

PS2摇杆控制方向。

[复制链接]
发表于 2012-9-20 02:13:43 | 显示全部楼层 |阅读模式
[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]
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则 需要先绑定手机号

Archiver|联系我们|极客工坊

GMT+8, 2024-4-30 07:13 , Processed in 0.053841 second(s), 17 queries .

Powered by Discuz! X3.4 Licensed

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表