I'm stuggling a little getting my head around the best way to do this.
I have a analog joystick and want to control a stepper motor with it.
I sort of have it working but it's clear to me the approach I've started with is not going to be best:
Hardware:
Arduino Mega
Easydriver 4.2
Joystick Shield
Serial LCD
Current Sketch: //Very basic to test everything and only goes "left" as such but not smoothly nor fast
//Vars for Joystick Shield
const byte PinX=0;
const byte PinY=1;
const byte Pin_Select=5;
int jy=0;
const int Y_THRESHOLD_LOW=500;
const int Y_THRESHOLD_HIGH=510;
//Vars for Easydriver
int dirpin = 23;
int steppin = 22;
int ms1=24;
void setup()
{
Serial.begin(9600);
Serial1.begin(9600);
backlightOn();
clearLCD();
pinMode(Pin_Select,INPUT);
digitalWrite(Pin_Select,HIGH);
pinMode(dirpin, OUTPUT);
pinMode(steppin, OUTPUT);
pinMode(ms1,OUTPUT);
//digitalWrite(ms1,LOW);
}
void loop()
{
selectLineOne();
clearLCD();
jy=checkJoy();
if (jy<Y_THRESHOLD_LOW){
Serial1.print("Left");
digitalWrite(steppin, LOW); // This LOW to HIGH change is what creates the
digitalWrite(steppin, HIGH); // "Rising Edge" so the easydriver knows to when to step.
}
if (jy<(Y_THRESHOLD_LOW-300)){
Serial1.print(" Faster");
}
if (jy>Y_THRESHOLD_HIGH){
Serial1.print("Right");
}
if (jy>(Y_THRESHOLD_HIGH+300)){
Serial1.print(" Faster");
}
if (jy>Y_THRESHOLD_LOW && jy<Y_THRESHOLD_HIGH){
Serial1.print("CENTERED");
}
selectLineTwo();
Serial1.print(digitalRead(Pin_Select));
}
int checkJoy(){
return analogRead(PinY);
}
void selectLineOne(){ //puts the cursor at line 0 char 0.
Serial1.write(0xFE); //command flag
Serial1.write(128); //position
delay(10);
}
void selectLineTwo(){ //puts the cursor at line 0 char 0.
Serial1.write(0xFE); //command flag
Serial1.write(192); //position
delay(10);
}
void goTo(int position) { //position = line 1: 0-15, line 2: 16-31, 31+ defaults back to 0
if (position<16){ Serial1.write(0xFE); //command flag
Serial1.write((position+128)); //position
}else if (position<32){Serial1.write(0xFE); //command flag
Serial1.write((position+48+128)); //position
} else { goTo(0); }
delay(10);
}
void clearLCD(){
Serial1.write(0xFE); //command flag
Serial1.write(0x01); //clear command.
delay(10);
}
void backlightOn(){ //turns on the backlight
Serial1.write(0x7C); //command flag for backlight stuff
Serial1.write(150); //light level.
delay(10);
}
void backlightOff(){ //turns off the backlight
Serial1.write(0x7C); //command flag for backlight stuff
Serial1.write(128); //light level for off.
delay(10);
}
void serCommand(){ //a general function to call the command flag for issuing all other commands
Serial1.write(0xFE);
}
Ultimately I want to use the joystick to move the motor and the joystick select button to set beginning and end points of rotation, then use another button to execute a continuous motion from beginning to end points.