Can someone please explain me the code below? I got this from the internet although I am not a hero in programming.
Basically I am trying to control a stepper motor with Arduino Uno, CNC Shield v3, stepper driver a4988 and joystick.
Further the stepper motor runs hot when not turning. For me the holding current is not important and this can be disabled. I have set V_REF using the potmeter on the stepper driver and used the formula V_REF = I_MOT8R_SENSE. R_SENSE is the resistor on the stepper driver.
Also it seems I can change the speed by changing the value after Serial.begin, e.g. the motor speed is increased when filling in 80000. Although when changing the number behind SMSpeed nothing happens.
Thanks for your help
// Stepper Motor X
const int stepPin = 2; //X.STEP
const int dirPin = 5; // X.DIR
// joystick
int button = A2;
int vrx = A0;
int vry = A1;
int vrx_data = 0;
int vry_data = 0;
int buttonf = 0;
int led5 = 13; // indicator
int x = 0;
int SMSpeed = 500; // Stepper Motor Speed
void setup() {
// Sets the two pins as Outputs
Serial.begin(9600);
pinMode(stepPin,OUTPUT);
pinMode(dirPin,OUTPUT);
pinMode(vrx , INPUT);
pinMode(vry, INPUT);
pinMode(button, INPUT);
digitalWrite(button , HIGH);
}
void loop() {
control();
if( buttonf == 1 )
{
joystick();
}
if( buttonf == 0 )
{
delay(100);
}
}
void control()
{
if (( digitalRead(button) == LOW ) && (buttonf == 0))
{
Serial.println(" Started");
digitalWrite(led5, HIGH);
buttonf = 1;
delay(1000);
}
if (( digitalRead(button) == LOW ) && (buttonf == 1))
{
digitalWrite(led5, LOW);
Serial.println("ended");
buttonf = 0;
delay(1000);
}
digitalWrite(button , HIGH);
}
void joystick()
{
vrx_data = analogRead(vrx);
Serial.print("Vrx:");
Serial.println(vrx_data);
// to stop the stepper motor
if ( (vrx_data > 490) && (vrx_data < 510) )
{
;
}
if ( vrx_data > 700 )
{
digitalWrite(dirPin,HIGH);
x = x + 1;
digitalWrite(stepPin,HIGH);
delayMicroseconds(SMSpeed);
digitalWrite(stepPin,LOW);
delayMicroseconds(SMSpeed);
}
if ( vrx_data < 300 )
{
digitalWrite(dirPin,LOW);
x = x - 1;
digitalWrite(stepPin,HIGH);
delayMicroseconds(SMSpeed);
digitalWrite(stepPin,LOW);
delayMicroseconds(SMSpeed);
}
}