The code is:
const int motorA1 = 8;
const int motorA2 = 9;
const int motorB1 = 10;
const int motorB2 = 11;
const int motorAe = 5;
const int motorBe = 6;
char speed = 100;
char change_speed_add = 30;
int command = 0;
void setup() {
pinMode(motorA1, OUTPUT);
pinMode(motorA2, OUTPUT);
pinMode(motorB1, OUTPUT);
pinMode(motorB2, OUTPUT);
pinMode(motorAe, OUTPUT);
pinMode(motorBe, OUTPUT);
analogWrite (motorAe , 0);
digitalWrite (motorA1,LOW);
digitalWrite (motorA2,LOW);
analogWrite (motorBe , 0);
digitalWrite (motorB1,LOW);
digitalWrite (motorB2,LOW);
Serial.begin(9600);
}
void loop() {
if (Serial.available() > 0){
command = Serial.read();
if (command == 70){
forward();}
else if (command == 76){
left();}
else if (command == 82){
right ();}
else if (command == 66){
reverse();}
else {
stop;}
Serial.println (command);
}
}
void forward(){
Serial.println ("fwd");
analogWrite(motorAe, speed);
analogWrite(motorBe, speed);
digitalWrite (motorA1, HIGH);
digitalWrite (motorB1, HIGH);
digitalWrite (motorA2, LOW);
digitalWrite (motorB2, LOW);
}
void reverse(){
Serial.println ("reverse");
analogWrite(motorAe, speed);
analogWrite(motorBe, speed);
digitalWrite (motorA1, LOW);
digitalWrite (motorB1, LOW);
digitalWrite (motorA2, HIGH);
digitalWrite (motorB2, HIGH);
}
void left(){
Serial.println ("left");
analogWrite(motorAe, speed +10);
analogWrite(motorBe, speed - 10);
digitalWrite (motorA1, LOW);
digitalWrite (motorA2, HIGH);
digitalWrite (motorB1, HIGH);
digitalWrite (motorB2, LOW);
}
void right(){
Serial.println ("right");
analogWrite(motorAe, speed -10);
analogWrite(motorBe, speed + 10);
digitalWrite (motorA1, HIGH);
digitalWrite (motorA2, LOW);
digitalWrite (motorB1, LOW);
digitalWrite (motorB2, HIGH);
}
void stop (){
Serial.println("stop");
analogWrite(motorAe, 0);
analogWrite(motorAe, 0);
digitalWrite (motorA1, LOW);
digitalWrite (motorA2, LOW);
digitalWrite (motorB1, LOW);
digitalWrite (motorB2, LOW);
}
No comments:
Post a Comment