HELP WITH CODE!

Hello,

Currency I have this code which I will attach. What I want to do is make it so I can change the speed of the motor within serial instead of coming off serial and just change it on the code manually. Hopefully someone can help me.

Here is the code :

#include <AFMotor.h>

AF_DCMotor motor(2,MOTOR12_1KHZ);
void setup() {
Serial.begin(9600);
Serial.flush();
Serial.print(“MOTOR SERIAL CONTROL TEST”);
motor.setSpeed(135);
motor.run(RELEASE);
}
void loop(){
if (Serial.available()) {

char ser = Serial.read();

if(ser == ‘1’){
Serial.print(“Up”);
motor.run(BACKWARD);//Put The Motor Going Backward
}
if(ser == ‘2’){
Serial.print("Down ");
motor.run(FORWARD);//Put The Motor Going Forward
}
if(ser == ‘0’){
Serial.print(“Stop”);
motor.run(RELEASE);//Stop The Motor
}
}
}

Many Thanks

Jamie

If you want to do it with minimal changes to the existing code, send a '+' or '-', and adjust the speed by say, 10% each time you get one of those codes.

Hello,

Thank you for your reply, how would I do this and where would I put it because I'm quite new to arduino and motors.

Many Thanks

Jamie

Step 1: Create a global variable for the motor speed. make it an unsigned int to give plenty of headroom for speed calculations

Step 2: Add a new if statement that looks for '+', if found, then execute: motorspeed = motorspeed * 11 /10;

Step 3: Add a new if statement that looks for '-', if found execute: motorspeed = motorspeed * 9 / 10;

Make sure you call the motor.setSpeed() method!

step 4: profit! Turn your assignment in for credit.

Changed the if’s into a switch statement which is easier to handle multiple if statements
added some emply lines to make it more readable
added extra commands for forward stop and reverse

#include <AFMotor.h>

AF_DCMotor motor(2,MOTOR12_1KHZ);

int speed = 0;

void setup() 
{
  Serial.begin(9600);
  Serial.flush();
  Serial.print("MOTOR SERIAL CONTROL TEST");
  motor.setSpeed(speed);
  motor.run(RELEASE);
}

void loop()
{
  if (Serial.available() > 0)
  {
    char ser = Serial.read();

    switch(ser)
    {
    case '1' : 
    case 'F' : // Forward
      Serial.println("UP");
      if (speed == 0) speed = 10;
      motor.run(FORWARD);
      break;
    case '2' : 
    case 'R' : // Reverse
      Serial.println("DOWN");
      if (speed == 0) speed = 10;
      motor.run(BACKWARD);
      break;
    case '3':
    case 'S': //Stop
      Serial.println("Stop");
      speed = 0;
      motor.run(RELEASE);
      break;
    case '+' :
      Serial.println("FASTER");
      if (speed < 240) speed += 10;  // assume max is 255
      break;
    case '-':
      Serial.println("SLOWER");
      if (speed > 10) speed -= 10;
      break;
    default: // do nothing
      break;
    }

    motor.setSpeed(speed);    
  }
}