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.

/**************************************************************************/
/*
    @file       DFR0722_V10_Demo.ino
    @author     PowerLiao (DFRobot)
    @version    V1.0
    @date       2020-07-09
    @copyright  Copyright (c) 2010 DFRobot Co.Ltd (http://www.dfrobot.com)
    @licence    The MIT License (MIT)
    @breif      This example read and print the 8421 encoder code.

    This demo and related libraries are for [DFR0722]8421 Encoder-Horizontal(V1.0)
    Check out the links below for tutorials and connection diagrams
    Product(CH): http://www.dfrobot.com.cn/
    Product(EN): 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