Mittwoch, 26. Dezember 2012

Time machine: Encoder.


Всем привет. Я не планировал описывать каждую деталь статьёй. Но энкодер стоит отдельного внимания. Для «Машины времени» я планировал купить самый доступный энкодер и использовать готовую библиотеку, коих на сайте Arduino много. Энкодер от Panasonic понравился наличием массивной ручки, в документации написано, что он long-life, что очень хорошо, размеры как раз подходят под мой корпус, очень привлекательная цена. Я купил пару штук EVEQDBRL416B и сделал под них платы. Когда я добрался до написания кода, оказалось, что ни одна библиотека на Arduino не работает с этим энкодером хорошо. У этого энкодера всего два состояния между переключениями. Фронт в канале «B» очень близко находится к месту фиксации, что добавляет проблемы при переключении. От небольшого нажима на ручку энкодера происходят ложные срабатывания. После небольших проб с готовыми библиотеками у меня возникло желание заменить этот энкодер на другой.
Но мысль о том, что надо переделывать уже готовые платы питания и интерфейса, останавливала открыть окно и выбросить энкодер. На написание библиотеки я потратил целый день. После третьего подхода получился очень простой обработчик энкодера.
Надеюсь эта библиотека будет полезной не только мне!!!
/*
  Pan_Encoder_ABC.cpp - A library for reading Encoder PANASONIC EVEQDBRL416B.

  Copyright 2012 Andrew Buckin(aka, "ka_ru"), except for the code at the end marked
  "The following was taken from the Arduino's code."  That portion is copyright by
  Andrew Buckin and is distributed under the GNU Lesser General Public License 2.1
  or any subsequent version.

  For those portions Copyright by Andrew Buckin, the following license applies.

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

    Questions?  Send mail to ka_ru2003@msn.com
*/

#include <PinChangeInt.h>

enum PinAssignments {
  encoderPinA = A2,   // rigth
  encoderPinB = A3,   // left
  clearButton = 8    // another two pins
};

volatile unsigned int encoderPos = 100;  // a counter for the dial
unsigned int lastReportedPos = 1;   // change management
static boolean rotating=false;      // debounce management

// interrupt service routine vars
volatile boolean ABc = false;
volatile boolean BBc = false;
volatile boolean AAc = false;
volatile boolean BAc = false;
int8_t clicks = 0;      // Counter to indicate cumulative clicks in either direction
int8_t direction = NULL;   // indicator
int8_t enc = NULL;   // indicator

void setup() {

  pinMode(encoderPinA, INPUT); 
  pinMode(encoderPinB, INPUT); 
  pinMode(clearButton, INPUT);
 // turn on pullup resistors
  digitalWrite(encoderPinA, HIGH);
  digitalWrite(encoderPinB, HIGH);
  digitalWrite(clearButton, HIGH);

  PCintPort::attachInterrupt(encoderPinA, &doEncoderA, CHANGE);
  PCintPort::attachInterrupt(encoderPinB, &doEncoderB, CHANGE);

  Serial.begin(9600);  // output
}

// main loop, work is done by interrupt service routines, this one only prints stuff
void loop() { 
  rotating = true;  // reset the debouncer
   
  if (direction != NULL){
   enc = !NULL;
    if (direction > 0) clicks++;
    else clicks--;
    direction = NULL;
  }
    
  if (enc != NULL) {
    Serial.print("Index:");
    Serial.println(encoderPos  + clicks, DEC);
    enc = NULL;
  }
 
  if (digitalRead(clearButton) == LOW )  {
    encoderPos = 0;
  }
}

// Interrupt on A changing state
void doEncoderA(){
  delayMicroseconds(50);
  AAc = digitalRead(encoderPinA);
  BAc = digitalRead(encoderPinB);
  if (!ABc && AAc && !BBc && !BAc){direction=1;}
  if (ABc && !AAc && BBc && BAc){direction=1;}
  if (!ABc && AAc && BBc && BAc){direction=-1;}
  if (ABc && !AAc && !BBc && !BAc){direction=-1;}

}

// Interrupt on B changing state
void doEncoderB(){
  delayMicroseconds(50);
  ABc = digitalRead(encoderPinA);
  BBc = digitalRead(encoderPinB);
}


Успешных вам кадров.
© Andrew Buckin.

Shutterstock Dreamstime
Fotostream http://www.flickr.com

Keine Kommentare:

Kommentar veröffentlichen