Example Code for Arduino-Direction & Interrupt Count
Last revision 2025/12/29
Direction & Interrupt count
Hardware Preparation
- DFRduino UNO (or similar) x 1
- Incremental Photoelectric Rotary Encoder
- 2x 1K Resistor
- M-M/F-M/F-F Jumper wires
Software Preparation
- Arduino IDE, Click to Download Arduino IDE from Arduino®
Wiring Diagram
Other Preparation Work
![]() |
Note: NPN open collector output needs pull-up resistors for the oscilloscope display. |
|---|
Sample Code
/*!
* @file SEN0230.ino
* @brief Two phase quadrature encoder(Incremental)
* @n To determine motor with encode (CW OR CCW)
* @copyright Copyright (c) 2010 DFRobot Co.Ltd (http://www.dfrobot.com)
* @license The MIT License (MIT)
* @author Dongzi([email protected])
* @version V1.0
* @date 2016-5-26
*/
#define A_PHASE 2
#define B_PHASE 3
unsigned int flagA = 0; //Assign a value to the token bit
unsigned int flagB = 0; //Assign a value to the token bit
/** * */
void setup() {
pinMode(A_PHASE, INPUT);
pinMode(B_PHASE, INPUT);
Serial.begin(9600); //Serial Port Baudrate: 9600
attachInterrupt(digitalPinToInterrupt( A_PHASE), interrupt, RISING); //Interrupt trigger mode: RISING
}
void loop() {
Serial.print("CCW: ");
Serial.println(flagA);
Serial.print("CW: ");
Serial.println(flagB);
delay(1000);// Direction judgement
}
void interrupt()// Interrupt function
{ char i;
i = digitalRead( B_PHASE);
if (i == 1)
flagA += 1;
else
flagB += 1;
}
Result
Use the interruption to detect the rotation direction and count cylinder number.
Was this article helpful?

