Posted on

Arduino Rotary Encoder Roboromania Tutorial pentru începători

Arduino Rotary Encoder Roboromania Tutorial pentru începători

default_comp26

O schema simpla :

Afișează pe serial poziția encoderului

rotary-encoder-arduino-tutorial-roboromania-wiring rotary-encoder-arduino-tutorial-roboromania

Și un cod simplu :

// Arduino Rotary Encoder Tutorial
int encoderCLK = 2;
int encoderDT = 4;

volatile int lastEncoded = 0;
volatile long encoderValue = 0;

long lastencoderValue = 0;

int lastMSB = 0;
int lastLSB = 0;

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

pinMode(encoderCLK, INPUT);
pinMode(encoderDT, INPUT);

digitalWrite(encoderCLK, HIGH); //turn pullup resistor on
digitalWrite(encoderDT, HIGH); //turn pullup resistor on

//call updateEncoder() when any high/low changed seen
//on interrupt 0 (pin 2), or interrupt 1 (pin 3)
attachInterrupt(0, updateEncoder, CHANGE);
attachInterrupt(1, updateEncoder, CHANGE);
}

void loop(){
Serial.println(encoderValue);
delay(10);
}

void updateEncoder(){
int MSB = digitalRead(encoderCLK); //MSB = most significant bit
int LSB = digitalRead(encoderDT); //LSB = least significant bit

int encoded = (MSB << 1) |LSB; //converting the 2 pin value to single number
int sum = (lastEncoded << 2) | encoded; //adding it to the previous encoded value

if(sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011) encoderValue ++;
if(sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000) encoderValue –;

lastEncoded = encoded; //store this value for next time
}

// Arduino Rotary Encoder Tutorial

Pentru butonul SW folosim exemplu clasic de la Arduino :

// Button
// set pin numbers:
const int buttonPin = 5; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin

// variables will change:
int buttonState = 0; // variable for reading the pushbutton status

void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
}

void loop() {
// read the state of the pushbutton value:
buttonState = digitalRead(buttonPin);

// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(ledPin, HIGH);
} else {
// turn LED off:
digitalWrite(ledPin, LOW);
}
}
// Button

Succes !

Colectivul Roboromania

Lasă un răspuns