Arduino with L298N

Arduino with L298N

Let us see how we could integrate Arduino with the L298N which is our motor controller. Now, it you are unsure about why we need an L298N H bridge, here is some background information about this! With that being said, our sketch looks like this:

 1/*
 2* DC Motor Encoder Test Sketch
 3* by Joesan [https://github.com/joesan]
 4* 27.12.2020
 5*
 6* Records encoder ticks for each wheel
 7* and prints the number of ticks for
 8* each encoder every 500ms
 9*
10* WARNING: This is a throw away sketch, it is here
11* just for experimental purposes.
12*
13*/
14// pins for the encoder inputs for Motor M1
15#define M1_ENCODER_A 3 // The yellow wire in the sketch above
16#define M1_ENCODER_B 4 // The green wire in the sketch above
17
18int enA = 8;
19int in1 = 9;
20int in2 = 10;
21
22// variable to record the number of encoder pulse
23volatile unsigned long m1Count = 0;
24double rpm = 0;
25unsigned long lastmillis = 0;
26
27void setup() {
28pinMode(M1_ENCODER_A, INPUT);
29pinMode(M1_ENCODER_B, INPUT);
30pinMode(enA, OUTPUT);
31pinMode(in1, OUTPUT);
32pinMode(in2, OUTPUT);
33
34// initialize hardware interrupt
35attachInterrupt(digitalPinToInterrupt(M1_ENCODER_A), m1EncoderEvent, RISING);
36
37Serial.begin(9600);
38}
39
40void loop() {
41// Turn on Motor A forward direction
42runForward(255);
43
44// Calculate the RPM every second
45if (millis() - lastmillis == 1000) {
46// Disable interrupt when calculating
47detachInterrupt(digitalPinToInterrupt(M1_ENCODER_A));
48
49    // rpm = counts / second * seconds / minute * revolutions / count
50    rpm = m1count * 60 / 979.62;      
51    Serial.print("RPM =\t");
52    Serial.println(rpm);  
53    m1Count = 0;
54    lastmillis = millis();
55
56    // Enable interrupt
57    attachInterrupt(digitalPinToInterrupt(M1_ENCODER_A), m1EncoderEvent, RISING);
58}
59}
60
61void runForward(int speed) { //speed 0-255
62analogWrite(enA, speed);
63digitalWrite(in1, HIGH);
64digitalWrite(in2, LOW);
65}
66
67void runBackward(int speed) { //speed 0-255
68analogWrite(enA, speed);
69digitalWrite(in1, LOW);
70digitalWrite(in2, HIGH);
71}
72
73void m1EncoderEvent() {
74m1Count++;
75}
76
77// encoder event for the interrupt call
78/*void m1EncoderEvent() {
79if (digitalRead(M1_ENCODER_A) == HIGH) {
80if (digitalRead(M1_ENCODER_B) == LOW) {
81m1Count++;
82} else {
83m1Count--;
84}
85} else {
86if (digitalRead(M1_ENCODER_B) == LOW) {
87m1Count--;
88} else {
89m1Count++;
90}
91} */
92}

That piece of code above deserves some basic explanation. Let us try to do that!

The important part to note about the code above is the use of the attachInterrput function. Have a look here for a very good explanation of the function parameters and its meaning!