#include <SoftwareSerial.h>
// Set up a software serial port for the HC-05, HC-06 Bluetooth module
SoftwareSerial BTserial(10, 11); // RX, TX
// Set up constants for the L298 control pins
const int in1 = 4; // MOTOR1 DIR
const int in2 = 5; // MOTOR1 DIR
const int enA = 6; // MOTOR1 SPEED
const int in3 = 7; // MOTOR2 DIR
const int in4 = 8; // MOTOR2 DIR
const int enB = 9; // MOTOR2 SPEED
void setup() {
// Initialize serial communication with the computer
Serial.begin(9600);
// Initialize serial communication with the HC-05
BTserial.begin(9600);
// Set up the L298 control pins as outputs
pinMode(enA, OUTPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(enB, OUTPUT);
pinMode(in3, OUTPUT);
pinMode(in4, OUTPUT);
}
void loop() {
// Check if there is data available from the HC-05
if (BTserial.available()) {
// Read a single character from the HC-05
char c = BTserial.read();
Serial.print(c);
// Check the character and control the L298 accordingly
switch (c) {
case 'f':
// Forward
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);
analogWrite(enA, 255); // Full speed
analogWrite(enB, 255); // Full speed
break;
case 'b':
// Backward
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);
digitalWrite(in3, LOW);
digitalWrite(in4, HIGH);
analogWrite(enA, 255); // Full speed
analogWrite(enB, 255); // Full speed
break;
case 's':
// Stop
digitalWrite(in1, LOW);
digitalWrite(in2, LOW);
digitalWrite(in3, LOW);
digitalWrite(in4, LOW);
analogWrite(enA, 0); // 0% duty cycle
analogWrite(enB, 0); // 0% duty cycle
break;
case '1':
// Low speed
analogWrite(enA, 128); // 50% duty cycle
analogWrite(enB, 128); // 50% duty cycle
break;
case '9':
// High speed
analogWrite(enA, 255); // 100% duty cycle
analogWrite(enB, 255); // 100% duty cycle
break;
default:
// Invalid command
break;
}
}
}