Example Code for Arduino-Read 8421 Encoder Code

This example read and print the 8421 encoder code.

Hardware Preparation

Software Preparation

Wiring Diagram

Connection Diagram

Sample Code

Upload the following codes to your mainboard, open the serial monitor, then you will find the output code value.

/**************************************************************************/
/*!
 * @file DFR0721_V10_Demo.ino
 * @brief This example read and print the 8421 encoder code.
 * @copyright  Copyright (c) 2010 DFRobot Co.Ltd (http://www.dfrobot.com)
 * @licence     The MIT License (MIT)
 * @author [PowerLiao]([email protected])
 * @version  V1.0
 * @date  2020-07-09
 * @get from https://www.dfrobot.com
*/

#define setbit(data,b) (data|=(1<<b)) //set the b bit of data to 1
#define clrbit(data,b) (data&=~(1<<b)) //set the b bit of data to 0

uint8_t code8421 = 0;
const uint8_t code8Pin = 5;
const uint8_t code4Pin = 4;
const uint8_t code2Pin = 3;
const uint8_t code1Pin = 2;

void setup() {
  Serial.begin(115200);
  Serial.println("8421 Encoder Starts up!");
  pinMode(code8Pin, INPUT);
  pinMode(code4Pin, INPUT);
  pinMode(code2Pin, INPUT);
  pinMode(code1Pin, INPUT);
}

void loop() {
  //According to the pin level and set the corresponding bit to 0 or 1
  if (digitalRead(code8Pin) == HIGH){
    setbit(code8421, 3);
  }else{
    clrbit(code8421, 3);
  }

  if (digitalRead(code4Pin) == HIGH){
    setbit(code8421, 2);
  }else{
    clrbit(code8421, 2);
  }

  if (digitalRead(code2Pin) == HIGH){
    setbit(code8421, 1);
  }else{
    clrbit(code8421, 1);
  }

  if (digitalRead(code1Pin) == HIGH){
    setbit(code8421, 0);
  }else{
    clrbit(code8421, 0);
  }

  //Output the code in hexadecimal 
  Serial.print("Now code8421 is:  ");
  Serial.println(code8421, HEX);
  delay(1000);
}

Result

The module print out the current code value every 1 second.

Result

Was this article helpful?

TOP