Arduino Projects‎ > ‎

Joystick Angle Game





Bill of Materials:
  • Aduino Micro
  • 20X4 LCD Display RT204-1(Ver3.0)
  • Parallax 2-Axis Joystick 27800 Rev B
  • 10k Potentiometer
  • Piezo Buzzer CET12A3.5
Arduino Sketch:

#include <Wire.h> 
#include <LiquidCrystal.h>
#include <math.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

double LR = 0;
double LRa = 0;
double LRc = 498;
double LRmax = 968;
double LRmin = 74;
double UD = 0;
double UDa = 0;
double UDc = 512;
double UDmax = 938;
double UDmin = 0;
double LRh = 0;
double LRl = 0;
double UDh = 0;
double UDl = 0;
double angleS = 0;
double x = 0;
double y = 0;
int angleT = 125;
int angleSd = 0;
int angleTol = 10;
int angleTmin = 110;
int angleTmax = 140;

void setup() {
  lcd.begin(20, 4);
  pinMode(13, OUTPUT);
  LRc = analogRead(0);
  UDc = analogRead(1);
  LRh = LRmax - LRc;
  LRl = LRc - LRmin;
  UDh = UDmax - UDc;
  UDl = UDc - UDmin;
  lcd.setCursor(0, 0);
  lcd.print(" Follow the Target!  ");
  lcd.setCursor(0, 1);
  lcd.print("Target Angle: ");
  lcd.setCursor(0, 2);
  lcd.print("Tolerance: +/- ");
  lcd.setCursor(0, 3);
  lcd.print("Signal Angle: ");
}

void loop() {
  LRa = analogRead(0);
  UDa = analogRead(1);
  if(LRa==LRc && UDa==UDc)
  {
    angleS = 0;
  }
  if(LRa==LRc && UDa>UDc)
  {  
    angleS = 90;
  }
  if(LRa==LRc && UDa<UDc)
  {
    angleS = 270;
  }
  if(LRa>LRc && UDa==UDc)
  {
    angleS = 0;
  }
  if(LRa>LRc && UDa>UDc)
  {
    LR = LRa - LRc;
    x = map(LR,0,LRh,0,250);
    UD = UDa - UDc;
    y = map(UD,0,UDh,0,250);
    angleS = atan2(y,x);
    angleS = angleS * 57295 / 1000;
  }
  if(LRa>LRc && UDa<UDc)
  {
    LR = LRa - LRc;
    x = map(LR,0,LRh,0,250);
    UD = UDc - UDa;
    y = map(UD,0,UDl,0,250);
    angleS = atan2(x,y);
    angleS = angleS * 57295 / 1000;
    angleS = angleS + 270;
  }
  if(LRa<LRc && UDa==UDc)
  {
    angleS = 180;
  }
  if(LRa<LRc && UDa>UDc)
  {
    LR = LRc - LRa;
    x = map(LR,0,LRl,0,250);
    UD = UDa - UDc;
    y = map(UD,0,UDh,0,250);
    angleS = atan2(x,y);
    angleS = angleS * 57295 / 1000;
    angleS = angleS + 90;
  }
  if(LRa<LRc && UDa<UDc)
  {
    LR = LRc - LRa;
    x = map(LR,0,LRl,0,250);
    UD = UDc - UDa;
    y = map(UD,0,UDl,0,250);
    angleS = atan2(y,x);
    angleS = angleS * 57295 / 1000;
    angleS = angleS + 180;
  }
  angleSd = angleS;
  if(angleSd >= angleTmin && angleSd <= angleTmax)
  {
    angleT = random(0,360);
    angleTol = random(1,10);
    angleTmin = angleT - angleTol;
    angleTmax = angleT + angleTol;
    analogWrite(13, 200);
    delay(100);
    analogWrite(13, 0);
    delay(100);
    analogWrite(13, 200);
    delay(100);
    analogWrite(13, 0);
    delay(100);
    analogWrite(13, 200);
    delay(100);
    analogWrite(13, 0);
  }
  lcd.setCursor(14, 1);
  lcd.print(angleT);
  lcd.print("  ");
  lcd.setCursor(15, 2);
  lcd.print(angleTol);
  lcd.print("  ");
  lcd.setCursor(14, 3);
  lcd.print(angleSd);
  lcd.print("  ");
  delay(250);
}
Comments