Problem with controlling stepper motor with keyboard?

I want to control my 3 stepper motors with my keyboard, now only 1 is connected.

  • Do I have to use the "serial monitor" and press send? Can't the Arduino program just directly send the keys I press?
  • This code will move the motor x steps, but only back and forth. I can't use the same key many times, only alternating left and right... Why is that?

This code is not my own, just copy/paste to have something to begin with.

#include <AccelStepper.h>

char key = 0;

int motorSpeed = 9600; //maximum steps per second (about 3rps / at 16 microsteps)
int motorAccel = 80000; //steps/second/second to accelerate

int motor1DirPin = 2; //digital pin 2
int motor1StepPin = 3; //digital pin 3

int motor2DirPin = 4; //digital pin 4
int motor2StepPin = 5; //digital pin 5

AccelStepper stepper1(1, motor1StepPin, motor1DirPin);
AccelStepper stepper2(1, motor2StepPin, motor2DirPin);


void setup(){
  stepper1.setMaxSpeed(motorSpeed);
  stepper2.setMaxSpeed(motorSpeed);

  stepper1.setSpeed(motorSpeed);
  stepper2.setSpeed(motorSpeed);

  stepper1.setAcceleration(motorAccel);
  stepper2.setAcceleration(motorAccel);
  
  //stepper1.moveTo(320); //move 32000 steps (should be 10 rev)
  //stepper2.moveTo(15000); //move 15000 steps
  Serial.begin(9600);
}

void loop(){

  if(Serial.available()>0)
  {
      key = Serial.read();
      Serial.print("Key: ");
      Serial.println(key, DEC);

     if(key == byte(97))
     {

       Serial.print("Left");
       stepper1.moveTo(3200);
       stepper1.run();

     }
     else if(key==byte(115))
     {
       Serial.print("Right");
       stepper1.moveTo(-3200);
       stepper1.run();
     }  
     stepper1.run();
}
  stepper1.run();
}

Larso:

  • Do I have to use the "serial monitor" and press send? Can't the Arduino program just directly send the keys I press?

This does not make sense to me. How could the arduino send keystrokes to itself from a keyboard on your PC?

Perhaps you need to write a specialized program for your PC to send appropriate data to the Arduino.

Or maybe you just need to connect two buttons to the Arduino - one for clockwise and one for counter-clockwise.

Take out all the lines with stepper1.run(); except the very last one (currently on line 57). The others are quite unnecessary.

The reason it only goes back and forth is that you only give it a value of 3200. You would need to add 3200 (to make 6400 etc) to make it move further. There is also a relative move function which may be what you need.

...R[/list]

The Arduino serial monitor doesn't send anything 'til you type [ENTER], you might try a terminal program like puTTy that sends keystrokes as you type.

http://www.putty.org/

Thanks for the help! The motor now works and I understand the serial a bit more :slight_smile: