#include "SoftwareSerial.h"
#include "DFRobotDFPlayerMini.h"
// Use pins 2 and 3 to communicate with DFPlayer Mini
static const uint8_t PIN_MP3_TX = 2; // Connects to module's RX
static const uint8_t PIN_MP3_RX = 3; // Connects to module's TX
SoftwareSerial softwareSerial(PIN_MP3_RX, PIN_MP3_TX);
// Create the Player object
DFRobotDFPlayerMini player;
/* define L298N or L293D motor control pins */
int In1 = A0; /* GPIO15(D8) -> IN1 */
int In2 = A1; /* GPIO13(D7) -> IN2 */
int In3 = A2; /* GPIO2(D4) -> IN3 */
int In4 = A3; /* GPIO0(D3) -> IN4 */
int obstaclePin = A5;
int hasObstacle = HIGH;
void setup()
{
pinMode(obstaclePin, INPUT);
/* initialize motor control pins as output */
pinMode(In3, OUTPUT);
pinMode(In1, OUTPUT);
pinMode(In4, OUTPUT);
pinMode(In2, OUTPUT);
// Init USB serial port for debugging
Serial.begin(9600);
// Init serial port for DFPlayer Mini
softwareSerial.begin(9600);
// Start communication with DFPlayer Mini
if (player.begin(softwareSerial)) {
Serial.println("OK");
// Set volume to maximum (0 to 30).
player.volume(30);
// Play the first MP3 file on the SD card
//player.play(1);
} else {
Serial.println("Connecting to DFPlayer Mini failed!");
}
}
void loop()
{
hasObstacle = digitalRead(obstaclePin);
if (hasObstacle == LOW)
{
MotorStop();
player.play(1);
delay(4000);
MotorBackward();
delay(300);
MotorStop();
delay(300);
player.play(1);
delay(3000);
TurnLeft();
delay(400);
}
else
{
MotorForward();
}
delay(200);
}
void MotorForward(void)
{
digitalWrite(In3,HIGH);
digitalWrite(In1,HIGH);
digitalWrite(In4,LOW);
digitalWrite(In2,LOW);
}
/********************************************* BACKWARD *****************************************************/
void MotorBackward(void)
{
digitalWrite(In4,HIGH);
digitalWrite(In2,HIGH);
digitalWrite(In3,LOW);
digitalWrite(In1,LOW);
}
/********************************************* TURN LEFT *****************************************************/
void TurnLeft(void)
{
digitalWrite(In3,LOW);
digitalWrite(In1,HIGH);
digitalWrite(In2,LOW);
digitalWrite(In4,HIGH);
}
/********************************************* TURN RIGHT *****************************************************/
void TurnRight(void)
{
digitalWrite(In3,HIGH);
digitalWrite(In1,LOW);
digitalWrite(In2,HIGH);
digitalWrite(In4,LOW);
}
/********************************************* STOP *****************************************************/
void MotorStop(void)
{
digitalWrite(In3,LOW);
digitalWrite(In4,LOW);
digitalWrite(In1,LOW);
digitalWrite(In2,LOW);
}
Comments