Энкодер управление меню на дисплее

Example Program

File > Examples > Encoder > TwoKnobs

/* Encoder Library - TwoKnobs Example
 * http://www.pjrc.com/teensy/td_libs_Encoder.html
 *
 * This example code is in the public domain.
 */

#include <Encoder.h>

// Change these pin numbers to the pins connected to your encoder.
//   Best Performance: both pins have interrupt capability
//   Good Performance: only the first pin has interrupt capability
//   Low Performance:  neither pin has interrupt capability
Encoder knobLeft(5, 6);
Encoder knobRight(7, 8);
//   avoid using pins with LEDs attached

void setup() {
  Serial.begin(9600);
  Serial.println("TwoKnobs Encoder Test:");
}

long positionLeft  = -999;
long positionRight = -999;

void loop() {
  long newLeft, newRight;
  newLeft = knobLeft.read();
  newRight = knobRight.read();
  if (newLeft != positionLeft || newRight != positionRight) {
    Serial.print("Left = ");
    Serial.print(newLeft);
    Serial.print(", Right = ");
    Serial.print(newRight);
    Serial.println();
    positionLeft = newLeft;
    positionRight = newRight;
  }
  // if a character is sent from the serial monitor,
  // reset both back to zero.
  if (Serial.available()) {
    Serial.read();
    Serial.println("Reset both knobs to zero");
    knobLeft.write(0);
    knobRight.write(0);
  }
}

Registers

You can use the registers defined in the spec to read position and
speed of the encoder. Other registers are used to write configuration
data such as changing the address, changing the termination state or
re-zeroing the encoder.

Reading Registers

Using the Wire library to read bytes from a register on a
device with address is as simple as:

Wire.beginTransmission(addr);
Wire.write(reg);
Wire.endTransmission();
Wire.requestFrom(address, N);
while (Wire.available()) {
  Wire.read(); // Do something with each byte.
}

Writing Registers

Using the Wire library to write byte to a register on a
device with address is as simple as:

Wire.beginTransmission(addr);
Wire.write(reg);
Wire.write(b);
Wire.endTransmission();

Low Performance Polling Mode

readread

With Arduino Uno, Duemilanove or Mega, Serial.print() can cause trouble.
Arduino 1.0 provides transmit buffering, which works much better than
Arduino 0023 and earlier. With either, a high speed baud rate should be
used, and minimizing the amount of data transmitted helps.

As of January 2012, Chipkit does not support attachInterrupt’s CHANGE mode
so low performance
polling mode is always used. Chipkit’s Serial.print() lacks transmit buffering
(same issue as Arduino Uno on pre-1.0 Arduino).
Chipkit does not support the pullup resistors, so you must provide
real resistors on both signals. The Chipkit developers have been contacted
regarding these issues. Hopefully future versions of MPIDE will fix these problems.

Hardware Requirements

Encoders have 2 signals, which must be connected to 2 pins. There are three
options.

  1. Best Performance: Both signals connect to interrupt pins.
  2. Good Performance: First signal connects to an interrupt pin, second to a non-interrupt pin.
  3. Low Performance: Both signals connect to non-interrupt pins,
    .
Board InterruptPins LED Pin(do not use)
Teensy 4.0 — 4.1 All Digital Pins 13
Teensy 3.0 — 3.6 All Digital Pins 13
Teensy LC 2 — 12, 14, 15, 20 — 23 13
Teensy 2.0 5, 6, 7, 8 11
Teensy 1.0 0, 1, 2, 3, 4, 6, 7, 16
Teensy++ 2.0 0, 1, 2, 3, 18, 19, 36, 37 6
Teensy++ 1.0 0, 1, 2, 3, 18, 19, 36, 37
Arduino Due All Digital Pins 13
Arduino Uno 2, 3 13
Arduino Leonardo 0, 1, 2, 3 13
Arduino Mega 2, 3, 18, 19, 20, 21 13
Sanguino 2, 10, 11

Low cost encoders only connect their pins to ground. Encoder will activate the
on-chip pullup resistors. If you connect lengthy wires, adding 1K pullup resistors
may provide a better signal.

Обработка сигналов энкодера с помощью прерываний

Сигналы энкодера должны быть обнаружены и интерпретированы в программе как можно быстрее, чтобы не блокировать основной поток программы. Мы можем детектировать сигналы путем опроса в основном цикле, или используя прерывания. Опрос не эффективен, так как вам необходимо зарезервировать время и ресурсы в основном цикле, что приводит к дополнительным задержкам. Использование прерываний – это более быстрое и экономичное решение. Мы покажем вам, как использовать прерывания для обработки сигналов энкодера.

В Atmega328 есть два типа прерываний, которые можно использовать для этих целей; внешнее прерывание и прерывание по изменению состояния вывода. Выводы и назначены на внешнее прерывание, а — назначены на прерывание по изменению состояния вывода. Внешнее прерывание может определить, произошел ли спад или нарастание входного сигнала, и может быть запущено при одном из следующих состояний: нарастание, спад или переключение. Для прерывания по изменению состояния выводов существует гораздо больше аппаратных ресурсов, но оно не может обнаруживать нарастающий и спадающий фронты, и оно вызывается, когда происходит любое изменение логического состояния (переключение) на выводе.

Чтобы использовать прерывание по изменению состояния выводов, подключите выходы поворота энкодера A и B к выводам и , а выход кнопки – к выводу платы Arduino, как показано на принципиальной схеме. Установите выводы , и в режим входа и включите их внутренние подтягивающие резисторы. Включите прерывание по изменению состояния выводов в регистре и включите прерывания для выводов , и в регистре . При обнаружении любого изменения логического состояния на одном из этих входов будет вызовано (прерывание по изменению состояния выводов).

Поскольку прерывание по изменению состояния выводов вызывается для любого логического изменения, нам необходимо отслеживать оба сигнала (и A, и B) и обнаруживать вращение при получение ожидаемой последовательности. Как видно из диаграммы сигналов, движение по часовой стрелке генерирует и . Когда мы записываем оба сигналы в байты и , сдвигая последнее чтение вправо, мы можем сравнить эти значения и определить новый шаг вращения.

Вы можете увидеть часть кода, включающую инициализацию и функцию обработки прерывания по изменению состояния выводов.

Использование внешнего прерывания делает процесс более простым, но поскольку для этого прерывания назначено только два вывода, то вы не сможете использовать его для других целей, если займете его энкодером. Чтобы использовать внешнее прерывание, вы должны установить выводы 2 () и 3 () в режим входа и включить их внутренние подтягивающие резисторы. Затем выберите вариант спадающего фронта для вызова обоих прерываний в регистре . Включите внешние прерывания в регистре . Когда начнется вращение вала энкодера, сначала ведущий сигнал падает до логического нуля, а второй сигнал некоторое время остается на уровне логической единицы. Поэтому нам нужно определить, какой из сигналов во время прерывания находится в состоянии логической единицы. После того, как ведущий сигнал упал до логического нуля, через некоторое время второй сигнал также упадет до логического нуля, что вызовет другое прерывание. Но этот раз и другой (ведущий) сигнал будет на низком логическом уровне, что означает, что это не начало вращения, поэтому мы игнорируем его.

Ниже вы можете увидеть часть кода, включающую в себя инициализацию и функцию обработки внешнего прерывания.

Макет для проверки кода работы с инкрементальным поворотным энкодером на Arduino

Полный код скетча Arduino, включающий основной цикл приведен ниже:

Энкодер в действии вы можете увидеть на видео, приведенном ниже:

Вот и всё! Надеюсь, статья оказалась полезной. Оставляйте комментарии!

How Rotary Encoders Work

Inside the encoder is a slotted disk connected to the common ground pin C, and two contact pins A and B, as illustrated below.

When you turn the knob, A and B come in contact with the common ground pin C, in a particular order according to the direction in which you are turning the knob.

When they come in contact with common ground they produce signals. These signals are shifted 90° out of phase with each other as one pin comes in contact before the other pin. This is called quadrature encoding.

When you turn the knob clockwise, the A pin connects first, followed by the B pin. When you turn the knob counterclockwise, the B pin connects first, followed by the A pin.

By tracking when each pin connects to and disconnects from the ground, we can use these signal changes to determine in which direction the knob is being rotated. You can do this by simply observing the state of B when A changes state.

When the A changes state:

  • if B != A, then the knob was turned clockwise.
  • if B = A, then the knob was turned counterclockwise.

Encoder

Circuit

The encoder is connected as follows:

  • ENC_A to A0
  • ENC_B to A1
Pin name Description Pin number
AREF  
A0 ENC0_A 1
A1 ENC0_B 2
A2 ENC1_A 3
A3 ENC1_B 4
A4 ENC2_A 5
A5 ENC2_B 6
A6 ENC3_A 7
D0 ENC3_B 8
D1 ENC4_A 9
D2 ENC4_B 10
D3 ENC5_A 11
D4 ENC5_B 12
D5 ENC6_A 13
D6 ENC6_B 14
D7 ENC7_A 15
D8 ENC7_B 16
D9 ENC8_A 17
D10 ENC8_B 18
D11 ENC9_A 19
D12 ENC9_B 20
D13 ENC10_A 21
D14 ENC10_B 22

Code

Include the VidorEncoder library, which is part of VidorPeripherals.

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

  • — refer to pinout tab for pinout (index) in this page
  • — resets the count value to «p»
  • — 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();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 = ; i < F_CPU 10; i++) {
    asm («nop»);
  }
  interrupts();#else
  delay(200);#endif
  if (value >= 200 || value <= -200) {
    // Reset the count
    encoder.write();
  }}

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

Arduino Code – Reading Rotary Encoders

Now that you have your encoder hooked up you’ll need a sketch to make it all work.

The following sketch detects when the encoder is being rotated, determines which direction it is being rotated and whether or not the button is being pushed.

Try the sketch out; and then we will dissect it in some detail.

If everything is fine, you should see below output on serial monitor.

If the rotation being reported is the opposite of what you expect, try swapping the CLK and DT lines.

Code Explanation:

The sketch begins with the declaration of the Arduino pins to which the encoder’s CLK, DT and SW pins are connected.

Next, a few integers are defined. The variable represents the count that will be modified each time that the knob is rotated one detent (click).

The and variables hold the state of the CLK output and are used for determining the amount of rotation.

A string called will be used when printing the current direction of rotation on the serial monitor.

The variable is used to debounce a switch.

Now in the Setup section, we first define the connections to the encoder as inputs, then we enable the input pullup resistor on SW pin. We also setup the serial monitor.

At the end we read the current value of the CLK pin and store it in the variable.

In the loop section, we check the CLK state again and compare it to the value. If they are different then it means that the knob has turned and a pulse has occurred. We also check if the value of is 1 in order to react to only one state change to avoid double count.

Inside the if statement we determine the direction of rotation. To do this we simply read the DT pin on the encoder module and compare it to the current state of the CLK pin.

If they are different, it means that the knob is rotated counterclockwise. We then decrement the counter and set to “CCW”.

If the two values are the same, it means that the knob is rotated clockwise. We then increment the counter and set to “CW”.

We then print our results on the serial monitor.

Outside the if statement we update with the current state of CLK.

Next comes the logic to read and debounce the push button switch. We first read the current button state, if it’s LOW, we wait for 50ms to debounce the push button.

If the button stays LOW for more than 50ms, we print “Button pressed!” message on the serial monitor.

Then we do it all over again.

Rotary Encoder Arduino Example

Let’s make a practical example of it using the Arduino. The particular module that I will use for this example comes on a breakout board and it has five pins. The first pin is the output A, the second pin is the output B, the third pin is the Button pin and of course the other two pins are the VCC and the GND pin.

We can connect the output pins to any digital pin of the Arduino Board.

You can get the components needed for this Arduino Tutorial from the links below:

  • Rotary Encoder Module………………. Amazon / Banggood
  • Arduino Board …………………………… Amazon / Banggood
  • Breadboard and Jump Wires ……… Amazon / Banggood

Disclosure: These are affiliate links. As an Amazon Associate I earn from qualifying purchases.

Control Servo Motor with Rotary Encoder

For our next project we will use a rotary encoder to control the position of a servo motor.

This project can be very useful in many situations, for example, when you want to operate a robot arm, as it would let you precisely position the arm and its grip.

In case you are not familiar with servo motor, consider reading (at least skimming) below tutorial.

SUGGESTED READING

Wiring

As the wiring diagram shows you’ll need a servo motor. Connect the Red wire of the servo motor to the external 5V supply, the Black/Brown wire to ground and the Orange/Yellow wire to the PWM enabled pin 9.

Of course you can use the Arduino 5V output but keep in mind that the servo can induce electrical noise onto the 5V line that the Arduino uses, which may not what you want.

Therefore it is recommended that you use an external power supply.

Arduino Code

Here’s the sketch to precisely control the servo motor with the rotary encoder. Each time the knob is rotated one detent (click), the position of the servo arm will be changed by one degree.

If you compare this sketch with our first one you’ll notice many similarities, except few things.

At the start we include the built-in Arduino Servo library and create a servo object to represent our servo motor.

In the Setup, we attach the servo object to pin 9 (to which the control pin of the servo motor is connected).

In the loop, we limit the counter to have a range 0 to 179, because a servo motor only accepts a value between this range.

Finally the counter value is used to position the servo motor.

Счет

Проанализировав состояние энкодера при вращении влево и вправо, составляем таблицу:

Его начальное положение 1-1. При повороте вправо произошел щелчок, единица стала логическим нулем. Новое значение this State vfd равно 01. Согласно команды данный результат суммируется со значением переменной Position.

Из-за того, что произошел дребезг, позиция стала 11, после перерасчета порядковый номер стал 7. После того, как дребезг закончился, нужно фиксировать новое положение 01 и к предыдущему нулю добавляется единица. При повороте энкодера произошел один щелчок, и значение переменной Position стало единицей.

Происходит второй щелчок при повороте энкодера направо, и вместо позиции 01 мы имеем позицию 00. После того, как весь дребезг закончится, на выходе управления также имеем значение единицы. При четвертом щелчке, когда позиция с 10 стала 11, мы имеем значение 6. После окончания дребезга остается 6.

В некоторых энкодерах имеет применение кнопка панели. При ее нажатии и отпускании тоже будет дребезг контактов, нужно применить библиотеку Bounce. Функции этой библиотеки нужны для задания pin, к которому будет подключена кнопка, задач времени задержки в миллисекундах. Если произошло нажатие на кнопку, то функция мощности (кВт) возвращает векторное значение true, если нет, то false vfd.

How Rotary Encoder Works

Let’s take a closer look at the encoder and see its working principle. Here’s how the square wave pulses are generated: The encoder has a disk with evenly spaced contact zones that are connected to the common pin C and two other separate contact pins A and B, as illustrated below.

When the disk will start rotating step by step, the pins A and B will start making contact with the common pin and the two square wave output signals will be generated accordingly.

Any of the two outputs can be used for determining the rotated position if we just count the pulses of the signal. However, if we want to determine the rotation direction as well, we need to consider both signals at the same time.

We can notice that the two output signals are displaced at 90 degrees out of phase from each other. If the encoder is rotating clockwise the output A will be ahead of output B.

So if we count the steps each time the signal changes, from High to Low or from Low to High, we can notice at that time the two output signals have opposite values. Vice versa, if the encoder is rotating counter clockwise, the output signals have equal values. So considering this, we can easily program our controller to read the encoder position and the rotation direction.

Example 2 – Controlling a Stepper Motor Using a Rotary Encoder

In addition to this basic example, I made one more example of controlling a stepper motor position using the rotary encoder.

Here’s the source code of this example:

/*     Stepper Motor using a Rotary Encoder
 *      
 *  by Dejan Nedelkovski, www.HowToMechatronics.com
 *  
 */

 #include <LiquidCrystal.h> // includes the LiquidCrystal Library 
 LiquidCrystal lcd(1, 2, 4, 5, 6, 7); // Creates an LC object. Parameters: (rs, enable, d4, d5, d6, d7) 

// defines pins numbers
 #define stepPin 8 
 #define dirPin  9
 #define outputA 10
 #define outputB 11

 int counter = 0;
 int angle = 0; 
 int aState;
 int aLastState;  
 
void setup() {
  // Sets the two pins as Outputs
  pinMode(stepPin,OUTPUT); 
  pinMode(dirPin,OUTPUT);
  pinMode (outputA,INPUT);
  pinMode (outputB,INPUT);
  
  aLastState = digitalRead(outputA);
  lcd.begin(16,2); // Initializes the interface to the LCD screen, and specifies the dimensions (width and height) of the display } 

}
void loop() {

  aState = digitalRead(outputA);
  
  if (aState != aLastState){     
     if (digitalRead(outputB) != aState) { 
       counter ++;
       angle ++;
       rotateCW();  
     }
     else {
       counter--;
       angle --;
       rotateCCW(); 
     }
     if (counter >=30 ) {
      counter =0;
     }
     
     lcd.clear();
     lcd.print("Position: ");
     lcd.print(int(angle*(-1.8)));
     lcd.print("deg"); 
     lcd.setCursor(0,0);
     
   }
  aLastState = aState;
}

void rotateCW() {
  digitalWrite(dirPin,LOW);
    digitalWrite(stepPin,HIGH);
    delayMicroseconds(2000);
    digitalWrite(stepPin,LOW);
    delayMicroseconds(2000); 
}
void rotateCCW() {
  digitalWrite(dirPin,HIGH);
    digitalWrite(stepPin,HIGH);
    delayMicroseconds(2000);
    digitalWrite(stepPin,LOW);
    delayMicroseconds(2000);   
}

Feel free to ask any question in the comments section below.

Maximum Speed and CPU Usage

File > Examples > Encoder > SpeedTest

Board MaximumInterrupt Rate(approximate) Conditions
Teensy 2.0 100 kHz Normal
Teensy 2.0 127 kHz ENCODER_OPTIMIZE_INTERRUPTS

Emulating Quadrature Encoded Signals

FreqCount

                        +5V
                         |        Quadrature Encoder Signal Emulator
 Clock                   |
 Input o----*--------------------------      ---------------------------o Output1
            |            |14           |    |
            |     _______|_______      |    |     _______________ 
            |    |    CD4013     |     |    |    |    CD4013     |
            |  5 |               | 1   |    |  9 |               | 13
        ---------|  D         Q  |-----|----*----|  D         Q  |------o Output2
       |    |    |               |     |         |               |
       |    |  3 |               |     |      11 |               |
       |     ----|> Clk          |      ---------|> Clk          |
       |         |               |               |               |
       |       6 |               |             8 |               |
       |     ----|  S            |           ----|  S            |
       |    |    |               |          |    |               |
       |    |  4 |            _  | 2        | 10 |            _  | 12
       |    *----|  R         Q  |---       *----|  R         Q  |----
       |    |    |               |          |    |               |    |
       |    |    |_______________|          |    |_______________|    |
       |    |            |                  |                         |
       |    |            | 7                |                         |
       |    |            |                  |                         |
        --------------------------------------------------------------
            |            |                  |
            |            |                  |
          -----        -----              -----
           ---          ---                ---
            -            -                  -

Measuring Maximum Interrupt Rates


SpeedTest: 147 mV (close to zero CPU remaining) at 127 kHz interrupt rate.

If using a mechanical system where
you reach a speed limit imposed by your motors or other hardware,
the amount this voltage has decreased, compared to the baseline,
should give you a good approximation of the portion of available
CPU time Encoder is consuming at your maximum speed.

Подключение инкрементного энкодера к Ардуино

пример создания такого меню

  • CLK и DT — выводы энкодера, они подтянуты к линии питания резисторами 10кОм;
  • SW — вывод кнопки, при нажатии вывод замыкается на землю;
  • + и GND — линии питания и земли. Данный энкодер является механическим, питание для него не требуется, линии нужны для цепи с подтягивающими резисторами.

Подключим энкодер к Ардуино по следующей схеме:

ссылка

#define pin_CLK 2
#define pin_DT  4
#define pin_Btn 3

unsigned long CurrentTime, LastTime;
enum eEncoderState {eNone, eLeft, eRight, eButton};
uint8_t EncoderA, EncoderB, EncoderAPrev;
int8_t counter;
bool ButtonPrev;

eEncoderState GetEncoderState() {
  
  eEncoderState Result = eNone;
  CurrentTime = millis();
  if (CurrentTime - LastTime >= 5) {
    
    LastTime = CurrentTime;
    if (digitalRead(pin_Btn) == LOW ) {
      if (ButtonPrev) {
        Result = eButton; 
        ButtonPrev = ;
      }
    }
    else {
      ButtonPrev = 1;
      EncoderA = digitalRead(pin_DT);
      EncoderB = digitalRead(pin_CLK);
      if ((!EncoderA) && (EncoderAPrev)) { 
        if (EncoderB) Result = eRight;     
        else          Result = eLeft;      
      }
      EncoderAPrev = EncoderA; 
    }
  }
  return Result;
}

void setup() {
  pinMode(pin_DT,  INPUT);
  pinMode(pin_CLK, INPUT);
  pinMode(pin_Btn, INPUT_PULLUP); 
  Serial.begin(9600);
  counter = ;
}

void loop() {
  switch (GetEncoderState()) {
    case eNone: return;
    case eLeft: {   
        counter--;
        break;
      }
    case eRight: {  
        counter++;
        break;
      }
    case eButton: { 
        counter = ;
        break;
      }
  }
  Serial.println(counter);
}
EncoderA = digitalRead(pin_CLK);
EncoderB = digitalRead(pin_DT);

Background

A typical mechanical rotary encoder emits a two bit gray code on 3 output pins. Every step in the output (often accompanied by a physical ‘click’) generates a specific sequence of output codes on the pins.

There are 3 pins used for the rotary encoding — one common and two ‘bit’ pins.

The following is the typical sequence of code on the output when moving from one step to the next:

From this table, we can see that when moving from one ‘click’ to the next, there are 4 changes in the output code.

  • From an initial 0 — 0, Bit1 goes high, Bit0 stays low.
  • Then both bits are high, halfway through the step.
  • Then Bit1 goes low, but Bit2 stays high.
  • Finally at the end of the step, both bits return to 0.

Detecting the direction is easy — the table simply goes in the other direction (read up instead of down).

To decode this, we use a simple state machine. Every time the output code changes, it follows state, until finally a full steps worth of code is received (in the correct order). At the final 0-0, it returns a value indicating a step in one direction or the other.

It’s also possible to use ‘half-step’ mode. This just emits an event at both the 0-0 and 1-1 positions. This might be useful for some encoders where you want to detect all positions. In rotary.h, uncomment to enable half-step mode.

If an invalid state happens (for example we go from ‘0-1’ straight to ‘1-0’), the state machine resets to the start until 0-0 and the next valid codes occur.

The biggest advantage of using a state machine over other algorithms is that this has inherent debounce built in. Other algorithms emit spurious output with switch bounce, but this one will simply flip between sub-states until the bounce settles, then continue along the state machine. A side effect of debounce is that fast rotations can cause steps to be skipped. By not requiring debounce, fast rotations can be accurately measured. Another advantage is the ability to properly handle bad state, such as due to EMI, etc. It is also a lot simpler than others — a static state table and less than 10 lines of logic.

Подключение энкодера промышленного назначения к Arduino

Наша задача суметь управлять скоростью асинхронного двигателя с помощью программы на компьютере. У нас имеется преобразователь частоты (частотник):

Для домашних заданий такая информация не нужна. На фотографии энкодер промышленного назначения для асинхронного двигателя управления мощностью (кВт) станков:

В станкостроении энкодеры широко применяются для преобразователей частоты асинхронных двигателей. Они монтируются как датчики обратной связи по своей скорости. Такие энкодеры имеют большую дискретность от 100 импульсов на оборот до 1 млн импульсов на оборот. У этой марки дискретность равна 500 имп. на оборот.

Энкодеры подразделяются на виды задач по принципу действия на частотные преобразователи. Они бывают абсолютными и инкрементальными. Наш энкодер выполняет обычную функцию – выдает сигнал дифференцирования при отключении мощности питания, и ее подачи снова. Раннее состояние не сохраняется.

Энкодеры абсолютного вида имеют внутреннюю память, которая помнит последние положения. Зачем нужна память, и зачем сохранять эти данные? В заводских условиях станкостроения перед перемещением определенного устройства в первую очередь указывают нулевую точку. Такой процесс называется реферированием, то есть, выход в нуль.

Применение датчика абсолютного вида дает возможность уйти от этой процедуры на второй раз, сократить время при условии, что система имеет ограничения для перемещений.

Рассмотрим энкодеры синуса и косинуса. Они выдают выходной сигнал косинуса или синуса. Далее, с помощью устройства интерполятора мощности образуют из них импульсы. Сигналы такого вида можно изменять в размерах. Питание энкодера осуществляется от напряжения 5 вольт.

Сигнал «А» — это сигнал импульса прямого типа. Количество импульсов с этого сигнала приходит на каждом обороте. Оно равно 500 (дискретность датчика).

Сигнал «В» — тоже прямой сигнал импульса. С него на каждом обороте поступает число импульсов по дискретности датчика, который смещен от канала «А» на 90 градусов (500).

Сигнал «R» — это сигнал метки «нуль». С одного оборота датчика получается один импульс.

В энкодерах промышленного назначения используется сигнал дифференцирования, для работы с частотным преобразователем (частотником). Название у него сложное, а на самом деле все просто. Все каналы отдельно копируются своей инверсией. Это необходимо для отдавания сигнала на значительные расстояния. Выходной канал энкодера подсоединяется к приемнику специального назначения, сделанному на усилителях операционного вида. Импульс в итоге определяется в совокупности двух сигналов.

Принципиальная схема подключения энкодера к преобразователю частоты

Данная схема состоит из платы Arduino Uno, инкрементального энкодера, четырехразрядного светодиодного индикатора, ключевых транзисторов и ограничительного резистора. Эта схема называется счетчиком импульсов. Она считает импульсы, которые будет воспроизводить энкодер при его вращении. Энкодер своими выводами подключен к каналам А2 и А3, вывод кнопки подключен к выводу А4, средний вывод подключен к земле, второй вывод тоже к земле.

Рассмотрим скетч, который называется счетчиком импульсов энкодера управления частотника. Вначале подключаем библиотеки для работы таймера, индикатора LS, для работы с энкодером, для кнопки.

Перейдем к макетной плате, и зальем все это в контроллер управления частотника. После заливания, включаем, крутим регулятор энкодера, цифры на экране возрастают. В обратную сторону векторного значения уменьшаются и переходят в отрицательную сторону. При увеличении серии задач отрицательного значения знак минуса смещается.

Если нажимаем на кнопку индикатора, переменная обнулится, на индикаторе будет ноль.

Оцените статью:
Оставить комментарий