Encoder

Hardware Required

Circuit

The encoder is connected as follows:

  • ENC_A to A0
  • ENC_B to A1


Pin nameDescriptionPin number
AREF 0
A0ENC0_A1
A1ENC0_B2
A2ENC1_A3
A3ENC1_B4
A4ENC2_A5
A5ENC2_B6
A6ENC3_A7
D0ENC3_B8
D1ENC4_A9
D2ENC4_B10
D3ENC5_A11
D4ENC5_B12
D5ENC6_A13
D6ENC6_B14
D7ENC7_A15
D8ENC7_B16
D9ENC8_A17
D10ENC8_B18
D11ENC9_A19
D12ENC9_B20
D13ENC10_A21
D14ENC10_B22


Code

Include the VidorEncoder library, which is part of VidorPeripherals.
#include "VidorPeripherals.h"
#include "VidorEncoder.h"

You have a number of functions available to manage the encoder:

  • VidorEncoder(int index) - refer to pinout tab for pinout (index) in this page
  • void write(int32_t p); - resets the count value to "p"
  • int32_t read(); - returns the actual count


/*
   This sketch shows how to use the Encoder IP in MKRVidor 4000
   Quadrature encoders are a very common way to detect position (and speed) of a moving part, like a DC motor.
   Normally, in the microcontroller world, decoding a quadrature encoder has serious limitations since all egdes must be counted, otherwise the final number will be wrong. This is usually accomplished using interrupts, but over a certain revolution speed the intinsic overhead of servicing an interrupt destroys the count reliability.

   Using the FPGA to perform decoding allows:
    - not to lose any edge until the revolution speed is less than some million RPM :)
    - we can "read" the encoder at any time, because the FPGA is counting independently

    Circuit:
      connect ENC_A to A0 and ENC_B to A1
*/


#include "VidorGraphics.h"
#include "VidorEncoder.h"

// Initialize Encoder #0 (connected to A0 and A1)
// Refer to the online documentation to find which pins correspond to a given index
// This assignment may change between bitstreams
VidorEncoder encoder(0);

void setup() {
  Serial.begin(9600);

  // wait for the serial monitor to open,
  // if you are powering the board from a USB charger remove the next line
  while (!Serial);

  // Let's start the FPGA
  if (!FPGA.begin()) {
    Serial.println("Initialization failed!");
    while (1) {}
  }
}

void loop() {

  // Read the encoder
  int value = encoder.read();
  Serial.print("Encoder value: ");
  Serial.println(value);

#if 1

  // Wait one second with interrupts disabled
  noInterrupts();
  // We can't call delay() since it uses interrupts, so use busy loops
  for (int i = 0; i < F_CPU / 10; i++) {
    asm ("nop");
  }
  interrupts();

#else
  delay(200);
#endif

  if (value >= 200 || value <= -200) {
    // Reset the count
    encoder.write(0);
  }
}


See Also

  • Enable Camera - Enables the video stream from a camera to an HDMI monitor
  • Draw Logo - Draw the Arduino Logo on an HDMI monitor
  • QR Recognition – The QR library allows you to recognize QR code markers and data


For more details on the Arduino MKR Vidor 4000, see the product page.

Last revision 2018/07/22 by SM