---
# System prepended metadata

title: 垃圾船-arduino blue tooth

---

# 垃圾船-arduino blue tooth

## Structure
![image](https://hackmd.io/_uploads/r15BeSIdR.png)


## Arduino code

```arduino=
#include <SoftwareSerial.h>

#define rxPin 11
#define txPin 12

int motor1pin1 = 2;
int motor1pin2 = 3;

int motor2pin1 = 4;
int motor2pin2 = 5;

SoftwareSerial BTSerial(rxPin, txPin);

void setup() {
  // put your setup code here, to run once:
  pinMode(motor1pin1, OUTPUT);
  pinMode(motor1pin2, OUTPUT);
  pinMode(motor2pin1, OUTPUT);
  pinMode(motor2pin2, OUTPUT);
  pinMode(9,  OUTPUT); 
  pinMode(10, OUTPUT);
  
  analogWrite(9,  0); //ENA pin
  analogWrite(10, 0); //ENB pin
  digitalWrite(motor1pin1, LOW);
  digitalWrite(motor1pin2, LOW);
  digitalWrite(motor2pin1, LOW);
  digitalWrite(motor2pin2, LOW);

  // Set the baud rate for the SoftwareSerial object
  pinMode(rxPin, INPUT);
  pinMode(txPin, OUTPUT);
  BTSerial.begin(9600);
  Serial.begin(9600);
}

void loop() {
  
  //Controlling speed (0   = off and 255 = max speed):     
  //(Optional)
  analogWrite(9,  200); //ENA pin
  analogWrite(10, 200); //ENB pin
  //(Optional)
  
  if(BTSerial.available()){
    char c = BTSerial.read();
    if (c == 'L') {                       // Left motor:  forward
      digitalWrite(motor1pin1, HIGH);
      digitalWrite(motor1pin2, LOW);
    } else if (c == 'P') {                // Left motor:  afterward
      digitalWrite(motor1pin1, LOW);
      digitalWrite(motor1pin2, HIGH);
    } else if (c == 'l' || c == 'p') {    // Left motor : halt
      digitalWrite(motor1pin1, LOW);
      digitalWrite(motor1pin2, LOW);
    } else if (c == 'R') {                // Right motor: forward
      digitalWrite(motor2pin1, LOW);
      digitalWrite(motor2pin2, HIGH);
    } else if (c == 'B') {                // Right motor: afterward
      digitalWrite(motor2pin1, HIGH);
      digitalWrite(motor2pin2, LOW);
    } else if (c == 'r' || c == 'b') {    // Right motor: halt
      digitalWrite(motor2pin1, LOW);
      digitalWrite(motor2pin2, LOW);
    }
  }
}
```

## Reference

SoftwareSerial Library:
https://docs.arduino.cc/learn/built-in-libraries/software-serial/

HC-06 Bluetooth:
https://projecthub.arduino.cc/RucksikaaR/interfacing-the-hc-06-bluetooth-module-with-arduino-94aabd

L298n Example:
https://projecthub.arduino.cc/lakshyajhalani56/l298n-motor-driver-arduino-motors-motor-driver-l298n-7e1b3b
