pdf-icon

Arduino Quick Start

2. Devices & Examples

6. Applications

Dial Rotary Encoder

APIs and example programs related to the Dial rotary encoder.

Example Program

Build Requirements

  • M5Stack board manager version >= 3.2.2
  • Board option = M5Dial
  • M5Dial library version >= 1.0.3
cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
#include "M5Dial.h"

long oldPosition = -999;

void setup() {
  auto cfg = M5.config();
  M5Dial.begin(cfg, true, false);  // encoder, RFID

  M5Dial.Display.setTextColor(GREEN);
  M5Dial.Display.setTextDatum(middle_center);
  M5Dial.Display.setTextFont(&fonts::Orbitron_Light_32);
  M5Dial.Display.setTextSize(2);
}

void loop() {
  M5Dial.update();

  long newPosition = M5Dial.Encoder.read();
  if (newPosition != oldPosition) {
    M5Dial.Speaker.tone(8000, 20);
    M5Dial.Display.clear();
    M5Dial.Display.drawString(String(newPosition),
                              M5Dial.Display.width() / 2,
                              M5Dial.Display.height() / 2);
    oldPosition = newPosition;
  }

  if (M5Dial.BtnA.wasPressed()) {
    M5Dial.Encoder.readAndReset();
  }
  if (M5Dial.BtnA.pressedFor(5000)) {
    M5Dial.Encoder.write(100);
  }
}

After compiling and uploading, the screen will display a number that follows the changes of the rotary encoder. Pressing the button briefly will reset the number to 0, and pressing and holding the button for 5 seconds will reset the number to 100.

begin

Function Prototype:

void begin();

Description:

  • Initialize the encoder IO.

When calling M5Dial.begin(), you can set the parameter enableEncoder to true to initialize it together.

M5Dial.begin(m5::M5Unified::config_t cfg, bool enableEncoder, bool enableRFID);

Input Parameters:

  • null

Return Value:

  • null

read

Function Prototype:

int32_t read();

Description:

  • Read the current encoder value.

Input Parameters:

  • null

Return Value:

  • int32_t: Current encoder value.

write

Function Prototype:

void write(int32_t p);

Description:

  • Write and update the encoder value.

Input Parameters:

  • int32_t p: Updated encoder value.

Return Value:

  • null

readAndReset

Function Prototype:

int32_t readAndReset();

Description:

  • Reset the current encoder value.

Input Parameters:

  • null

Return Value:

  • int32_t: Encoder value before reset
On This Page