Coche Bluetooth con Arduino Uno + HC-05 (L298N)
Conduce un coche de dos ruedas por Bluetooth con el joystick del móvil; se monta con Arduino Uno, HC-05, L298N y dos motores, sin internet. Solo Android: el iPhone no puede conectarse al HC-05; para iPhone usa un HM-10. Vincula el HC-05 en los ajustes de Bluetooth del móvil, ve a Mi Taller › Dispositivos › Añadir dispositivo › Bluetooth, elige Arduino Uno + HC-05/06 y Mando de coche y sube el código de Obtener el código.

Video
Diagrama del circuito

Código fuente
1// ┌────────────────────────────────────┐
2// │ BlueGrays · bluegrays.com │
3// │ Bluetooth · Arduino Uno + HC-05/06 │
4// │ BG-Araba │
5// └────────────────────────────────────┘
6// Mando de coche
7// Placa en Arduino IDE: Arduino Uno
8// El HC-05/06 es Bluetooth clásico: solo Android, el iPhone no puede conectarse. El nombre se cambia en modo AT (opcional).
9
10#include <SoftwareSerial.h>
11
12const char BLE_NAME[] = "BG-Araba"; // la placa se anuncia con este nombre y la app la encuentra así en la lista
13
14// Pines: cámbialos aquí si conectaste de otra forma
15const int ENA = 5, IN1 = 7, IN2 = 8; // El motor A (ENA, IN1, IN2) es la rueda izquierda y el motor B (ENB, IN3, IN4) la derecha
16const int ENB = 6, IN3 = 9, IN4 = 10;
17const unsigned long COMMAND_TIMEOUT_MS = 500; // Seguridad: si no llega ningún comando en 500 ms, los motores se paran (la app lo repite mientras conduces)
18
19void btWrite(const char *text);
20void onValue(const char *key, const char *value);
21void sendAll();
22void onLinkLost();
23
24// ── La app envía líneas "clave=valor"; con "?" la placa manda todos sus valores ──
25char line[65];
26uint8_t lineLen = 0;
27unsigned long lastRxMs = 0;
28
29bool is(const char *a, const char *b) { return strcmp(a, b) == 0; }
30bool isOn(const char *v) { return v[0] == '1'; }
31
32void sendText(const char *key, const char *value) {
33 char out[72];
34 snprintf(out, sizeof(out), "%s=%s\n", key, value);
35 btWrite(out);
36}
37
38void sendInt(const char *key, long value) {
39 char text[12];
40 snprintf(text, sizeof(text), "%ld", value);
41 sendText(key, text);
42}
43
44void sendFloat(const char *key, float value) {
45 char text[16];
46 dtostrf(value, 1, 1, text);
47 sendText(key, text);
48}
49
50void handleLine(char *text) {
51 char *eq = strchr(text, '=');
52 if (eq == nullptr) {
53 if (text[strlen(text) - 1] == '?') {
54 btWrite("@v=1.0\n"); // la línea "@v" indica a la app la versión del código
55 sendAll();
56 }
57 return;
58 }
59 *eq = '\0';
60 onValue(text, eq + 1);
61}
62
63void feed(char c) {
64 lastRxMs = millis();
65 if (c == '\n' || c == '\r') {
66 if (lineLen == 0) return;
67 line[lineLen] = '\0';
68 lineLen = 0;
69 handleLine(line);
70 } else if (lineLen < sizeof(line) - 1) {
71 line[lineLen++] = c;
72 }
73}
74
75// ── Bluetooth (SoftwareSerial) ──
76SoftwareSerial bt(2, 3); // módulo TXD → D2, RXD → D3 (con divisor 1k/2k), 9600 baudios
77
78void btWrite(const char *text) { bt.print(text); }
79
80void btBegin() { bt.begin(9600); }
81
82void btPoll() {
83 while (bt.available()) feed(bt.read());
84}
85
86// ── Arduino Uno + HC-05/06 ──
87int speedLimit = 80; // límite de velocidad desde la app (0–100 %)
88unsigned long lastCommandMs = 0;
89bool moving = false;
90
91// si el coche va hacia atrás, intercambia los dos cables de ese motor
92void motor(int en, int a, int b, int power) {
93 power = constrain(power, -100, 100);
94 digitalWrite(a, power > 0 ? HIGH : LOW);
95 digitalWrite(b, power < 0 ? HIGH : LOW);
96 analogWrite(en, abs(power) * speedLimit * 255L / 10000);
97}
98
99void drive(int left, int right) {
100 motor(ENA, IN1, IN2, left);
101 motor(ENB, IN3, IN4, right);
102 moving = left != 0 || right != 0;
103 lastCommandMs = millis();
104}
105
106void onValue(const char *key, const char *value) {
107 if (is(key, "joy")) { // Joystick: y adelante/atrás, x gira; se convierte en velocidad de rueda izquierda y derecha
108 const char *comma = strchr(value, ',');
109 int x = atoi(value), y = comma ? atoi(comma + 1) : 0;
110 drive(constrain(y + x, -100, 100), constrain(y - x, -100, 100));
111 } else if (is(key, "yon")) {
112 if (is(value, "ileri")) drive(100, 100);
113 else if (is(value, "geri")) drive(-100, -100);
114 else if (is(value, "sol")) drive(-70, 70);
115 else if (is(value, "sag")) drive(70, -70);
116 else drive(0, 0);
117 } else if (is(key, "hiz")) {
118 speedLimit = constrain(atoi(value), 0, 100);
119 }
120}
121
122void sendAll() {
123 sendInt("hiz", speedLimit);
124}
125
126void onLinkLost() {
127 drive(0, 0); // Conexión perdida: los motores se paran
128}
129
130void setup() {
131 Serial.begin(115200);
132 int pins[] = { ENA, IN1, IN2, ENB, IN3, IN4 };
133 for (int pin : pins) pinMode(pin, OUTPUT);
134 drive(0, 0);
135 btBegin();
136 Serial.print(F("BlueGrays Bluetooth: "));
137 Serial.println(BLE_NAME);
138}
139
140void loop() {
141 btPoll();
142 if (moving && millis() - lastCommandMs > COMMAND_TIMEOUT_MS) drive(0, 0);
143}
144Preguntas frecuentes
¿Funciona con iPhone?
No, este proyecto solo funciona en Android. El HC-05 usa Bluetooth clásico, y el iPhone no puede conectarse a módulos de Bluetooth clásico. Para iPhone usa un HM-10: en la app eliges Arduino Uno + HM-10 como placa. La guía del coche Bluetooth con ESP32, que ya trae Bluetooth integrado, también funciona en iPhone. En Android, primero vincula el HC-05 en los ajustes de Bluetooth del móvil (el PIN suele ser 1234 o 0000) y luego conéctate desde la app.
¿En qué se diferencia del antiguo coche Bluetooth con L298N?
En el antiguo proyecto #80, el coche controlado por Bluetooth con L298N (HC-05, 4 motores), el coche recibía órdenes de una sola letra como F, B, L y R desde una app de mando de terceros. Este proyecto funciona con el panel Bluetooth propio de BlueGrays: giros suaves con el joystick, un control de velocidad máxima y una parada de seguridad cuando dejan de llegar órdenes. La app prepara el código para la placa que elijas.
¿Cómo alimento el Uno? ¿Pueden estar conectados el USB y la batería a la vez?
Las 2 baterías 18650 (7,4 V) van a la entrada 12V del L298N, y la salida 5V del L298N alimenta el pin 5V del Uno; para ello el jumper del regulador de 5V del L298N debe seguir puesto. Todos los GND deben estar unidos. Si el USB está conectado mientras subes el código, apaga la batería o quita el cable de 5V que viene del L298N, o las dos fuentes chocarán. El HC-05 va en D2 y D3, así que no tienes que quitarlo para subir el código.
¿Qué alcance tiene? ¿Qué hace el coche si se corta la conexión?
El HC-05 llega a unos 10 metros al aire libre; las paredes y las personas en medio lo acortan. Mientras conduces, la app repite la orden sin parar, y si la placa no recibe ninguna en 500 ms, para los motores. El HC-05 no avisa al Uno cuando se corta la conexión; gracias a este tiempo de seguridad, el coche se para en medio segundo si se pierde el enlace. Para volver a conectarte, elige de nuevo tu HC-05 en la app.
