-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArduino_Car.cpp
More file actions
101 lines (90 loc) · 1.68 KB
/
Arduino_Car.cpp
File metadata and controls
101 lines (90 loc) · 1.68 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
#include <Arduino.h>
#include <RC_Receiver.h>
void mpower(int motor, int spd);
RC_Receiver receiver(A0, A1);
int minMax[2][2] =
{
{-255, 255},
{-255, 255},
};
int enA = 5;
int in1 = 2;
int in2 = 3;
int enB = 6;
int in3 = 4;
int in4 = 7;
void setup()
{
Serial.begin(115200);
pinMode(enA, OUTPUT);
pinMode(in1, OUTPUT);
pinMode(in2, OUTPUT);
pinMode(enB, OUTPUT);
pinMode(in3, OUTPUT);
pinMode(in4, OUTPUT);
receiver.setMinMax(minMax); // set the min and max value for each channels
Serial.println("Ready");
}
void loop()
{
int forwardSpeed = map(receiver.getRaw(2), 1989, 1015, -255, 255); // Forward/Backward
int turnSpeed = map(receiver.getRaw(1), 1983, 1000, -255, 255); // Left/Right
// Control the motors based on joystick input
int leftMotorSpeed = forwardSpeed + turnSpeed;
int rightMotorSpeed = forwardSpeed - turnSpeed;
mpower(1, rightMotorSpeed); // Control left motors
mpower(2, leftMotorSpeed); // Control right motors
Serial.println(receiver.getRaw(1));
}
void mpower(int motor, int spd)
{
int rotation = 0;
if (spd > 0)
{
rotation = 1;
}
else if (spd < 0)
{
rotation = -1;
spd *= -1;
}
if (spd > 255)
{
spd = 255;
}
int pwm;
int pA;
int pB;
if (motor == 1)
{
pwm = enA;
pA = in1;
pB = in2;
}
else if (motor == 2)
{
pwm = enB;
pA = in3;
pB = in4;
}
else
{
return;
}
if (rotation == 0)
{
digitalWrite(pA, LOW);
digitalWrite(pB, LOW);
}
else if (rotation == 1)
{
digitalWrite(pA, HIGH);
digitalWrite(pB, LOW);
}
else if (rotation == -1)
{
digitalWrite(pA, LOW);
digitalWrite(pB, HIGH);
}
analogWrite(pwm, spd);
}