Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#include <SoftwareSerial.h>
#include <Wire.h>
SoftwareSerial CAR_BT(11,12); //定義 PIN11 及 PIN12 分別為 RX 及 TX 腳位
/* Input for leftMotor:
IN1 IN2 Action
LOW LOW Stop
HIGH LOW Forward
LOW HIGH Backward
HIGH HIGH Stop
*/
const int leftMotorIn1 = 5;
const int leftMotorIn2 = 6;
/* Input for rightMotor:
IN3 IN4 Action
LOW LOW Stop
HIGH LOW Forward
LOW HIGH Backward
HIGH HIGH Stop
*/
const int rightMotorIn3 = 9;
const int rightMotorIn4 = 10;
bool isForward = true;
void setup()
{
pinMode(leftMotorIn1, OUTPUT);
pinMode(leftMotorIn2, OUTPUT);
pinMode(rightMotorIn3, OUTPUT);
pinMode(rightMotorIn4, OUTPUT);
Serial.begin(9600); //Arduino起始鮑率:9600
CAR_BT.begin(9600); //藍牙鮑率:9600 注意!每個藍牙晶片的鮑率都不太一樣,請務必確認
}
void loop()
{
int inSize;
char input;
if( (inSize = (CAR_BT.available())) > 0) { //讀取藍牙訊息
Serial.print("size = ");
Serial.println(inSize);
Serial.print("Input = ");
Serial.println(input=(char)CAR_BT.read());
if( input == 'f' ) {
forward();
isForward = true;
}
if( input == 'b' ) {
backward();
isForward = false;
}
if( input == 'l' ) {
left();
}
if( input == 'r' ) {
right();
}
if( input == 's' ) {
motorstop();
}
}
}
void motorstop()
{
digitalWrite(leftMotorIn1, LOW);
digitalWrite(leftMotorIn2, LOW);
digitalWrite(rightMotorIn3, LOW);
digitalWrite(rightMotorIn4, LOW);
}
void forward()
{
digitalWrite(leftMotorIn1, HIGH);
digitalWrite(leftMotorIn2, LOW);
digitalWrite(rightMotorIn3, HIGH);
digitalWrite(rightMotorIn4, LOW);
}
void backward()
{
digitalWrite(leftMotorIn1, LOW);
digitalWrite(leftMotorIn2, HIGH);
digitalWrite(rightMotorIn3, LOW);
digitalWrite(rightMotorIn4, HIGH);
}
void right()
{
if( isForward ) {
digitalWrite(leftMotorIn1, HIGH);
digitalWrite(leftMotorIn2, LOW);
digitalWrite(rightMotorIn3, LOW);
digitalWrite(rightMotorIn4, LOW);
} else {
digitalWrite(leftMotorIn1, LOW);
digitalWrite(leftMotorIn2, LOW);
digitalWrite(rightMotorIn3, LOW);
digitalWrite(rightMotorIn4, HIGH);
}
}
void left()
{
if( isForward ) {
digitalWrite(leftMotorIn1, LOW);
digitalWrite(leftMotorIn2, LOW);
digitalWrite(rightMotorIn3, HIGH);
digitalWrite(rightMotorIn4, LOW);
} else {
digitalWrite(leftMotorIn1, LOW);
digitalWrite(leftMotorIn2, HIGH);
digitalWrite(rightMotorIn3, LOW);
digitalWrite(rightMotorIn4, LOW);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.