Repository navigation
Expand file tree
/
Copy pathmain.cpp
More file actions
512 lines (454 loc) · 14.7 KB
/
Copy pathmain.cpp
File metadata and controls
512 lines (454 loc) · 14.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
/*
-- Progetto Secondo Modulo di Sistemi --
La macchina è un robot mobile autonomo a 4 ruote motrici indipendenti con:
- Sensore ad ultrasuoni montato su un servo per scansione a 3 direzioni (sinistra, centro, destra)
- Quattro motori DC per il movimento delle ruote
- Display OLED per feedback visivo
- Logica di navigazione autonoma basata su distanze rilevate
Info: shield utilizzata per muovere i motori delle ruote
https://wiki.dfrobot.com/2A_Motor_Shield_For_Arduino_Twin___SKU_DRI0017_
@ autore: Mattia Floriani 4^Asr anno scolastico 2025/26
@ versione: V.6
@ data ultima modifica: 04/02/2026
*/
/** ________________________
| *VARIABILI* |
|_______________________|
**/
#include <Arduino.h>
#include <Servo.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_I2C_ADDRESS 0x3C
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
Adafruit_SSD1306 oled(SCREEN_WIDTH, SCREEN_HEIGHT);
// Dichiarazione degli stati di funzionamento
enum State {
Init, // Inizializza la macchina
Scan, // Ruota il servo motore, misura la distanza
Decide, // Confronta le distanze, decide la direzione migliore
MForward, // Motori in avanti + controllo sensore dritto
TRight, // Sterza a destra
TLeft, // Sterza a sinistra
Escape, // Gestisce un eventuale vicolo cieco o altrimenti dà lo stop e segna di allarme
Stop // Robot fermo
};
State idState = Init;
// Dichiarazione stati motore
enum MotorCommand {
MotorStop, // Motore fermo
MotorAvanti, // Motore in Avanti
MotorIndietro, // Motore in dietro
MTurnLeft, // Motore gira a Sinistra
MTurnRight // Motore gira a Destra
};
// Struct per salvare misurazioni delle distanze
struct Distance {
int left;
int center;
int right;
};
Distance dist = { 0, 0, 0 };
// Variabili motore
const int E1Pin = 10;
const int M1Pin = 12;
const int E2Pin = 11;
const int M2Pin = 13;
typedef struct {
byte enPin;
byte directionPin;
} MotorControl;
const int M1 = 0;
const int M2 = 1;
const int motorNum = 2;
const MotorControl motorPin[] = { { E1Pin, M1Pin }, { E2Pin, M2Pin } };
const int Forward = LOW;
const int Backward = HIGH;
// sensore HC-SR04
#define TRIG_PIN 6
#define ECHO_PIN 7
long pulseDuration; // durata impulso in microsecondi misurata da pulseIn()
int distanceCm; // distanza calcolata in centimetri (-1 = fuori portata)
const unsigned long pulseTimeout = 38000UL; // massimo range
// Soglie critiche (valori in cm) - calibrare in base a velocità e dimensioni robot
const int sogliaCritica = 25; // sotto questa distanza fermarsi immediatamente (es. 25cm)
const int sogliaVicina = 30; // considerato "vicino" nella decisione (es. 30cm)
const int sogliaLibera = 45; // soglia per considerare la via libera (es. >45cm)
// Servo (angoli in gradi) - calibrare in base al montaggio fisico del sensore
Servo myServo;
const int servoLeft = 165; // posizione massimo a sinistra
const int servoCenter = 90; // posizione centrale
const int servoRight = 15; // posizione massimo a destra
#define PIN_SERVO 9 // pin servo
// Variabili sterzata
// durataRotazione: tempo in ms per completare la rotazione calibrata (~90°)
// Calibrare aumentando/diminuendo questo valore se la rotazione non corrisponde.
const unsigned long durataRotazione = 400; // ms (es. 350-450 a seconda del robot)
unsigned long movimentoTimer = 0;
bool movimentoInCorso = false;
// Variabili escape
bool escapeInProgress = false;
unsigned long escapeTimer = 0;
// Temporizzazioni stampa su seriale
unsigned long serialTimer = 0;
/*bitmap per la presentazione
utilizzato questo convertitore di bitmap
https://en.radzio.dxp.pl/bitmap_converter/
*/
// Array che contiene la bitmap che viene utilizzata nella presentazione di benvenuto
const unsigned char PROGMEM car1[] = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xC0, 0x00, 0x00, 0x3F, 0xFC, 0x00, 0x00, 0x3F, 0xFC,
0x10, 0x00, 0xF3, 0xCF, 0x18, 0x00, 0xE3, 0xC7, 0x0C, 0x00, 0xC3, 0xC3, 0x06, 0x00, 0xC3, 0xC3,
0x03, 0x00, 0xFE, 0x7F, 0x01, 0x00, 0x7E, 0x7F, 0x01, 0x00, 0x03, 0xC0, 0x01, 0x00, 0x03, 0xC0,
0x01, 0x00, 0x03, 0xC0, 0x01, 0x00, 0x03, 0xC0, 0x01, 0xFF, 0xC3, 0xC0, 0x01, 0xFF, 0xC3, 0xC0,
0x01, 0x00, 0x43, 0xC0, 0x01, 0xFF, 0xC3, 0xC0, 0x7F, 0xFF, 0xFF, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF,
0x0F, 0xFF, 0xFF, 0xF0, 0x0F, 0xFF, 0xFF, 0xF0, 0x0F, 0xFF, 0xFF, 0xF0, 0x0F, 0xFF, 0xFF, 0xF0,
0x18, 0x60, 0x06, 0x18, 0x3F, 0xF8, 0x1F, 0xFC, 0x43, 0x08, 0x10, 0xC2, 0xDB, 0x6C, 0x36, 0xDB,
0xDB, 0x6C, 0x36, 0xDB, 0x43, 0x08, 0x10, 0xC2, 0x3F, 0xF8, 0x1F, 0xFE, 0x18, 0x60, 0x06, 0x18
};
//Dichiarazione funzioni
void gestioneStati();
void aggiornaDisplay();
const char* getNomeStato(State stato);
void benvenuto();
void printSerial();
void motore(MotorCommand comando);
void initMotor();
void setMotorDirection(int motorNumber, int direction);
inline void setMotorSpeed(int motorNumber, int speed);
bool scanAmbiente();
int prendiDistanza();
State decideProssimoStato();
bool tunnelCieco();
bool avantiLibero();
bool ostacoloCritico();
bool movimentoFinito();
bool eseguiEscape();
/** ________________________
| *SETUP* |
|_______________________|
**/
void setup() {
Serial.begin(9600);
if (!oled.begin(SSD1306_SWITCHCAPVCC, SCREEN_I2C_ADDRESS)) {
Serial.print(F("Errore inizializzazione SSD1306"));
while (true)
;
}
// Inizializza Motori
initMotor();
// Gestione servo e sensore
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
myServo.attach(PIN_SERVO);
}
/** ________________________
| *Gestione LOOP* |
|_______________________|
**/
void loop() {
gestioneStati();
aggiornaDisplay();
printSerial();
}
/** _____________________________
| *Gestione Funzioni* |
|___________________________|
**/
//----------Gestione stati macchina------------
void gestioneStati() {
switch (idState) {
//Stato di inizializzazione e di Benvenuto su Dispaly
case Init:
Serial.println("BENVENUTO NELLA SERIALE DELLA ROBOT CAR");
myServo.write(servoCenter); //inizializza il servo posizione centrale
benvenuto();
delay(500);
idState = Scan;
break;
//Stato che scannerizza le tre posizioni prestabilite
case Scan:
if (scanAmbiente()) {
delay(50);
idState = Decide;
}
break;
//Stato che gestisce la logica e individua la miore via di fuga
case Decide:
idState = decideProssimoStato();
break;
//Motori avanti + controllo da parte del sensore eventuali nuovi ostacoli
case MForward:
motore(MotorAvanti);
if (ostacoloCritico()) {
motore(MotorStop);
idState = Scan;
}
break;
//Girare a sinistra per il tempo prestabilito
case TLeft:
motore(MTurnLeft);
if (movimentoFinito()) {
motore(MotorStop);
delay(100);
idState = Scan;
}
break;
//Girare a destra per il tempo prestabilito
case TRight:
motore(MTurnRight);
if (movimentoFinito()) {
motore(MotorStop);
delay(100);
idState = Scan;
}
break;
//Stato che gestisce un eventuale vivolo cieco
case Escape:
if (eseguiEscape()) {
idState = Scan;
}
break;
//Stato stop : non implementato
case Stop:
motore(MotorStop);
break;
}
}
// ----------Funzioni Dispaly e Seriale ------------
// Gestione Display
void aggiornaDisplay() {
oled.clearDisplay();
oled.setTextSize(1); //gestione grandezza carattere
oled.setTextColor(SSD1306_WHITE);
oled.setCursor(2, 6);
oled.print("Stato: ");
//passo lo stato variabile per aver return char da stampare a video
oled.setCursor(40, 1);
oled.setTextSize(2);
oled.println(getNomeStato(idState));
oled.setTextSize(1);
oled.setCursor(20, 20);
oled.print("L:"); // misirazione presa a sinistra
oled.print(dist.left);
oled.print(" C:");
oled.print(dist.center); // misirazione presa in centro
oled.print(" R:");
oled.println(dist.right); // misirazione presa a destra
oled.setTextSize(2);
oled.setCursor(8, 35);
oled.print("DF cm:");
oled.print(distanceCm);
oled.display();
}
// funzione che mi restituisce un char con il nome dello stato da stampare a video
const char* getNomeStato(State stato) {
switch (stato) {
case Init: return "INIT";
case Scan: return "SCAN";
case Decide: return "DECIDE";
case MForward: return "AVANTI";
case TLeft: return "SINISTRA";
case TRight: return "DESTRA";
case Escape: return "ESCAPE";
case Stop: return "STOP";
default: return "?";
}
}
// funzione che gestisce una piccola presentazione iniziale
void benvenuto() {
oled.clearDisplay();
oled.setTextSize(2);
oled.setTextColor(SSD1306_WHITE);
oled.setCursor(2, 2);
oled.println("IlRobotCar");
oled.setTextSize(1);
oled.setCursor(2, 18);
oled.println("Mattia Floriani 4 Asr");
//animazione presentazione
for (int i = -32; i <= 140; i += 4) { //For che fa muove la bitmap
oled.clearDisplay(); // Cancella frame precedente
oled.setTextSize(2);
oled.setCursor(2, 2);
oled.println("IlRobotCar");
oled.setTextSize(1);
oled.setCursor(2, 18);
oled.println("Mattia Floriani 4 Asr");
oled.drawBitmap(i, 30, car1, 32, 32, SSD1306_WHITE);
oled.setTextSize(2);
oled.setCursor(i - 100, 40);
oled.println("loading");
oled.display(); // Aggiorna lo schermo per ogni frame
delay(100);
}
}
//Gestione e stampa informazioni sulla Seriale
void printSerial() {
unsigned long now = millis();
if (now - serialTimer > 1000) {
serialTimer = now; // aggiorna solo quando scaduto l'intervallo(timer non bloccante)
Serial.print("Stato: ");
Serial.println(getNomeStato(idState));
Serial.print("Misurazioni: L / C / R : ");
Serial.print(dist.left);
Serial.print(" - ");
Serial.print(dist.center);
Serial.print(" - ");
Serial.print(dist.right);
Serial.println(" !");
Serial.print("Distanza: impatto frontale: ");
Serial.print(distanceCm);
Serial.println(" Cm");
Serial.println(" --- ");
}
}
//----------Funzioni Motore------------
// funzioni gestione motori ruote
void motore(MotorCommand comando) {
switch (comando) {
case MotorStop:
// stato motori off
setMotorSpeed(M1, 0);
setMotorSpeed(M2, 0);
break;
case MotorAvanti:
// stato motori avanti motore M1 e M2 impostati a Forward
setMotorDirection(M1, Forward);
setMotorSpeed(M1, 100);
setMotorDirection(M2, Forward);
setMotorSpeed(M2, 100);
break;
case MotorIndietro:
// stato motori indietro motore M1 e M2 impostati a Backward
setMotorDirection(M1, Backward);
setMotorSpeed(M1, 100);
setMotorDirection(M2, Backward);
setMotorSpeed(M2, 100);
break;
case MTurnLeft:
// stato motori ruota robot a sinistra motori funzionamento invertiti
setMotorDirection(M1, Backward);
setMotorSpeed(M1, 100);
setMotorDirection(M2, Forward);
setMotorSpeed(M2, 100);
break;
// stato motori ruota robot a detra motori funzionamento invertiti
case MTurnRight:
setMotorDirection(M1, Forward);
setMotorSpeed(M1, 100);
setMotorDirection(M2, Backward);
setMotorSpeed(M2, 100);
break;
}
}
// inizializzazione motori
void initMotor() {
for (int i = 0; i < motorNum; i++) {
pinMode(motorPin[i].enPin, OUTPUT);
pinMode(motorPin[i].directionPin, OUTPUT);
digitalWrite(motorPin[i].enPin, LOW);
}
}
// funzio gestione senso di rotazione motori
void setMotorDirection(int motorNumber, int direction) {
digitalWrite(motorPin[motorNumber].directionPin, direction);
}
// funzio gestione gestione velocità e rotazione motori
inline void setMotorSpeed(int motorNumber, int speed) {
analogWrite(motorPin[motorNumber].enPin, 255.0 * (speed / 100.0));
}
//----------Funzioni Gestione Servo + Sensore Ultra Suoni------------
//funzione gestione lo stato Scan
bool scanAmbiente() {
int tempoDelay = 1100;
myServo.write(servoLeft);
delay(tempoDelay);
dist.left = prendiDistanza(); // ottieni valore ultrasonico e salva in dist.left
myServo.write(servoCenter);
delay(tempoDelay);
dist.center = prendiDistanza(); // ottieni valore ultrasonico e salva in dist.center
myServo.write(servoRight);
delay(tempoDelay);
dist.right = prendiDistanza(); // ottieni valore ultrasonico e salva in dist.right
myServo.write(servoCenter);
delay(tempoDelay);
return true;
}
// funzione che restituisce valore distanza grazie al sensore ad ultra suoni
int prendiDistanza() {
// Dare un corto segnale basso per poi dare un segnale alto puro:
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
//invia un impulso di 10 microsec su trigger
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
pulseDuration = pulseIn(ECHO_PIN, HIGH, pulseTimeout);
// Converti il tempo in distanza (cm):
if (pulseDuration == 0) {
distanceCm = -1;
} else {
distanceCm = (0.034 * pulseDuration) / 2;
}
return distanceCm;
}
//----------Funzioni Logiche e Decisionali------------
//funzione per il confronto
State decideProssimoStato() {
if (tunnelCieco()) {
return Escape;
}
if (avantiLibero()) {
return MForward;
}
if (dist.left > dist.right) {
return TLeft;
}
return TRight;
}
//tunnelCieco restituisce true se tutte le condizioni sono vere
bool tunnelCieco() {
return (dist.left < sogliaVicina && dist.center < sogliaVicina && dist.right < sogliaVicina);
}
//avantiLibero restituisce true se la via danti e libera
bool avantiLibero() {
return dist.center > sogliaLibera;
}
/*ostacoloCritico restituisce: true se difronte al robotCar trova un ostacolo */
bool ostacoloCritico() {
int temp = prendiDistanza(); //chiamata alla funzione prende distanza
return temp < sogliaCritica;
}
// Funzione che temporizza il movimento di sterzata
bool movimentoFinito() {
if (!movimentoInCorso) {
movimentoInCorso = true;
movimentoTimer = millis();
return false;
}
if (millis() - movimentoTimer >= durataRotazione) {
movimentoInCorso = false;
return true;
}
return false;
}
/* funzione che gestisce un eventuale uscita da un vicolo cieco,
in prima battuta fa partire un timer e inizia a retrocede,
quando il timer raggiunge 600ms effettua una rotazione a sinistra,
quando il timer raggiunge 900ms la funzione fa entrare il robotCar in stato di Scan*/
bool eseguiEscape() {
if (!escapeInProgress) {
escapeInProgress = true;
escapeTimer = millis();
motore(MotorIndietro);
}
if (millis() - escapeTimer > 500) {
motore(MTurnLeft);
}
if (millis() - escapeTimer > 800) {
motore(MotorStop);
escapeInProgress = false;
return true;
}
return false;
}