Example Code for Arduino-Motor Validation
This tutorial can be used to validate the motor or to understand how the motor works.
Hardware Preparation
- DFRduino Romeo‐All in one Controller (or similar) x 1
- 6V Power Supply x 1
- Jumper wires
Software Preparation
Wiring Diagram
Motor 6V power supply wiring(correspond to example1)
Other Preparation Work
In this tutorial, D2 and D3 are selected, D2 is the interrupt pin and D3 is the signal input pin.
In practice, we just need to ensure one interrupt pin, and the other pin can be self-defined (see master of the interrupt pin in the figure below)
Notcie: attachInterrupt()
For example, if you want to use interrupt pin 0 (interrupt 0) on UNO, you can connect the number 2 digital pin (D2); With Interrupt Pin 1 (Interrupt 1), you can connect number 3 digital pin (D3).
Sample Code
/*!
* @file FIT052X.ino
* @brief Metal DC Motor Encoder - 6V
* @n Data is constantly output from the serial port. When the motor turns clockwise, the output value > 0; when the motor turns counterclockwise, the output value < 0.
* @n The faster the motor, the greater the absolute value of the number, otherwise the lower the motor, the smaller the absolute value of the number.
* @copyright Copyright (c) 2010 DFRobot Co.Ltd (http://www.dfrobot.com)
* @license The MIT License (MIT)
* @author DFRobot
* @version V1.0
* @date 2023-08-03
*/
//The sample code for driving one way motor encoder
const byte encoder0pinA = 2;//A pin -> the interrupt pin 0
const byte encoder0pinB = 3;//B pin -> the digital pin 3
byte encoder0PinALast;
int duration;//the number of the pulses
boolean Direction;//the rotation direction
void setup()
{
Serial.begin(57600);//Initialize the serial port
EncoderInit();//Initialize the module
}
void loop()
{
Serial.print("Pulse:");
Serial.println(duration);
duration = 0;
delay(100);
}
void EncoderInit()
{
Direction = true;//default -> Forward
pinMode(encoder0pinB, INPUT);
attachInterrupt(0, wheelSpeed, CHANGE);
}
void wheelSpeed()
{
int Lstate = digitalRead(encoder0pinA);
if ((encoder0PinALast == LOW) && Lstate == HIGH) {
int val = digitalRead(encoder0pinB);
if (val == LOW && Direction) {
Direction = false; //Reverse
} else if (val == HIGH && !Direction) {
Direction = true; //Forward
}
}
encoder0PinALast = Lstate;
if (!Direction) duration++;
else duration--;
}
Result
Data is constantly output from the serial port. When the motor turns clockwise, the output value > 0; when the motor turns counterclockwise, the output value < 0. The faster the motor, the greater the absolute value of the number, otherwise the lower the motor, the smaller the absolute value of the number.
Was this article helpful?
