//Joystick setup
int JoyStick_X = A0; //x
int JoyStick_Y = A1; //y
//button setup
const int buttonpin=2;
int buttonState=0;
int val = 0;
//Motor 1 set up
const int enA = 3;
const int in1=4;
const int in2=5;
//Motor 2 set up
const int enB=6;
const int in3=7;
const int in4=8;
int motorSpeedA;
int motorSpeedB;
void setup()
{
pinMode(enA, OUTPUT);
pinMode(enB, OUTPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(in3, OUTPUT);
pinMode(in4, OUTPUT);
pinMode(JoyStick_X,INPUT);
pinMode(JoyStick_Y,INPUT);
pinMode(buttonpin,INPUT);
Serial.begin(9600); // 9600 bps
}
void loop()
{
int x,y;
x=analogRead(JoyStick_X);
y=analogRead(JoyStick_Y);
Serial.print(x ,DEC);
Serial.print(",");
Serial.print(y ,DEC);
Serial.print(",");
Serial.print(val);
delay(100);
buttonState=digitalRead(buttonpin);
if(buttonState==HIGH){
val=val++;
if(val>=2){val=0;}
}
if(val=0){
if(y<470){//down
digitalWrite(in1,HIGH);
digitalWrite(in2,LOW);
//motor b
digitalWrite(in3,HIGH);
digitalWrite(in4,LOW);
motorSpeedA = map(y, 470, 0, 0, 255);
motorSpeedB = map(y, 470, 0, 0, 255);
}
else if(y>550){
// Set Motor A forward
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
// Set Motor B forward
digitalWrite(in3, LOW);
digitalWrite(in4, HIGH);
// Convert the increasing Y-axis readings for going forward from 550 to 1023 into 0 to 255 value for the PWM signal for increasing the motor speed
motorSpeedA = map(y, 550, 1023, 0, 255);
motorSpeedB = map(y, 550, 1023, 0, 255);
}
else{
motorSpeedA=0;
motorSpeedB=0;
}
if (x < 470) {
// Convert the declining X-axis readings from 470 to 0 into increasing 0 to 255 value
int xMapped = map(x, 470, 0, 0, 255);
// Move to left - decrease left motor speed, increase right motor speed
motorSpeedA = motorSpeedA - xMapped;
motorSpeedB = motorSpeedB + xMapped;
// Confine the range from 0 to 255
if (motorSpeedA < 0) {
motorSpeedA = 0;
}
if (motorSpeedB > 255) {
motorSpeedB = 255;
}
}
if (x >550){
// Convert the increasing X-axis readings from 550 to 1023 into 0 to 255 value
int xMapped = map(x, 550, 1023, 0, 255);
// Move right - decrease right motor speed, increase left motor speed
motorSpeedA = motorSpeedA + xMapped;
motorSpeedB = motorSpeedB - xMapped;
// Confine the range from 0 to 255
if (motorSpeedA > 255) {
motorSpeedA = 255;
}
if (motorSpeedB < 0) {
motorSpeedB = 0;
}
}
}
if(val=1){//servo movement
}
}