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
| // Motor A
#define leftSpeedPin 16 // Left motor speed control, to PWM_A
#define leftDir1 14 // Left motor direction 1, to AIn1
#define leftDir2 15 // Left motor direction 2, to AIn2
// Motor B
#define rightDir1 17 // Right motor direction 1, to BIn1
#define rightDir2 18 // Right motor direction 2, to BIn2
#define rightSpeedPin 19 // Right motor speed control, to PWM_B
// setup
void setup() {
int motorSpeed; // From 0->255, slow->fast.
// Set motor direction pins as outputs.
pinMode(leftDir1, OUTPUT);
pinMode(leftDir2, OUTPUT);
pinMode(rightDir1, OUTPUT);
pinMode(rightDir2, OUTPUT);
// Serial
Serial.begin(9600);
Serial.println("Robot ready for mission:");
}
// Loop all day long...
void loop() {
// Listen for incoming messages
if (Serial.available() > 0 ) {
char command = Serial.read();
// Motor A
if(command == '1') { fmotor('A'); }
if(command == '2') { bmotor('A'); }
if(command == '5') { stopmotor('A'); }
// Motor B
if(command == '3') { fmotor('B'); }
if(command == '4') { bmotor('B'); }
if(command == '6') { stopmotor('B'); }
// Debug
Serial.println(command);
}
}
/* *********************************************************
*
* Functions
*
* *********************************************************/
// Go go go...
void fmotor(char motor) {
if (motor == 'A') {
digitalWrite(leftSpeedPin, HIGH);
digitalWrite(leftDir1, HIGH);
digitalWrite(leftDir2, LOW);
analogWrite(leftSpeedPin, 200);
}
if (motor == 'B') {
digitalWrite(rightSpeedPin, HIGH);
digitalWrite(rightDir1, HIGH);
digitalWrite(rightDir2, LOW);
analogWrite(rightSpeedPin, 200);
}
}
// Run motor backword
void bmotor(char motor) {
if (motor == 'A') {
digitalWrite(leftSpeedPin, HIGH);
digitalWrite(leftDir1, LOW);
digitalWrite(leftDir2, HIGH);
analogWrite(leftSpeedPin, 200);
}
if (motor == 'B') {
digitalWrite(rightSpeedPin, HIGH);
digitalWrite(rightDir1, LOW);
digitalWrite(rightDir2, HIGH);
analogWrite(rightSpeedPin, 200);
}
}
// Ohoy, stop all motoros!
void stopmotor(char motor) {
if (motor == 'A') {
digitalWrite(leftSpeedPin, LOW);
digitalWrite(leftDir1, LOW);
digitalWrite(leftDir2, LOW);
}
if (motor == 'B') {
digitalWrite(rightSpeedPin, LOW);
digitalWrite(rightDir1, LOW);
digitalWrite(rightDir2, LOW);
}
}
|