-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathN20_gearmotor_with_encoder.ino
More file actions
53 lines (41 loc) · 934 Bytes
/
N20_gearmotor_with_encoder.ino
File metadata and controls
53 lines (41 loc) · 934 Bytes
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
#include <Encoder.h>
// Motor Driver Pins
int PWMA = 5;
int AIN1 = 4;
int AIN2 = 3;
int STBY = 11;
// Encoder Pins
int encoderC1 = A0;
int encoderC2 = A1;
// Motor Speed
int motorSpeed = 100;
int maxMotorSpeed = 255;
// Create Encoder Object
Encoder motorEncoder(encoderC1, encoderC2);
void setup() {
Serial.begin(115200);
pinMode(PWMA, OUTPUT);
pinMode(AIN1, OUTPUT);
pinMode(AIN2, OUTPUT);
pinMode(STBY, OUTPUT);
digitalWrite(STBY, HIGH); // Enable motor driver
}
void loop() {
// Read Encoder Position
long pos = motorEncoder.read();
Serial.print("Encoder Position: ");
Serial.println(pos);
// Move Motor Forward
moveMotor(motorSpeed);
delay(100); // Small delay for stability
}
void moveMotor(int speed) {
digitalWrite(AIN1, HIGH);
digitalWrite(AIN2, LOW);
analogWrite(PWMA, speed);
}
void stopMotor() {
digitalWrite(AIN1, LOW);
digitalWrite(AIN2, LOW);
analogWrite(PWMA, 0);
}