Hardware components | ||||||
| × | 1 | ||||
| × | 1 | ||||
| × | 1 | ||||
Software apps and online services | ||||||
|
In this video I will show you how to use Rotary Encodedrs with Arduino Interrupts.It is quite fascinating that this component looking similar to the rotary potentiometer is actually totally different.Hope you would find this tutorial useful.
If you have never used potentiometer with Arduino probably you want to view this tutorial first:
And here is Rotary Encoder tutorial:
int counter=0;
String dir="";
unsigned long last_run=0;
void setup() {
Serial.begin(9600);
attachInterrupt(digitalPinToInterrupt(3), shaft_moved, FALLING);
pinMode(4,INPUT);
}
void shaft_moved(){
if (millis()-last_run>5){
if (digitalRead(4)==1){
counter++;
dir="CW";
}
if (digitalRead(4)==0){
counter--;
dir="CCW";}
last_run=millis();
}
}
void loop() {
Serial.print("counter : ");
Serial.print(counter);
Serial.print(" direction : ");
Serial.println(dir);
}
int counter=5;
String dir="";
unsigned long last_run=0;
void setup() {
Serial.begin(9600);
attachInterrupt(digitalPinToInterrupt(3), shaft_moved, FALLING);
pinMode(4,INPUT);
}
void shaft_moved(){
if (millis()-last_run>5){
if (digitalRead(4)==1){
if(counter<10) counter++;
dir="CW";
}
if (digitalRead(4)==0){
if (counter>5) counter--;
dir="CCW";}
last_run=millis();
}
}
void loop() {
Serial.print("counter : ");
Serial.print(counter);
Serial.print(" direction : ");
Serial.println(dir);
}
int DS1_pin = 6;
int STCP1_pin =9;
int SHCP1_pin = 8 ;
int DT_pin = 5;
int counter=0;
unsigned long last_run=0;
int digits [10][8]{
{0,1,1,1,1,1,1,0}, // digit 0
{0,0,1,1,0,0,0,0}, // digit 1
{0,1,1,0,1,1,0,1}, // digit 2
{0,1,1,1,1,0,0,1}, // digit 3
{0,0,1,1,0,0,1,1}, // digit 4
{0,1,0,1,1,0,1,1}, // digit 5
{0,1,0,1,1,1,1,1}, // digit 6
{0,1,1,1,0,0,0,0}, // digit 7
{0,1,1,1,1,1,1,1}, // digit 8
{0,1,1,1,1,0,1,1} // digit 9
};
void DisplayDigit(int Digit)
{
digitalWrite(STCP1_pin,LOW);
for (int i = 7; i>=0; i--)
{
digitalWrite(SHCP1_pin,LOW);
if (digits[Digit][i]==1) digitalWrite(DS1_pin, LOW);
if (digits[Digit][i]==0) digitalWrite(DS1_pin, HIGH);
digitalWrite(SHCP1_pin,HIGH);
}
digitalWrite(STCP1_pin, HIGH);
}
void shaft_moved(){
if (millis()-last_run>5){
if (digitalRead(4)==1){
if (counter<9) counter++;
}
if (digitalRead(4)==0){
if(counter>0) counter--;
}
last_run=millis();
}
}
void reset_to_0(){
counter=0;
}
void setup() {
pinMode(DS1_pin, OUTPUT);
pinMode(STCP1_pin, OUTPUT);
pinMode(SHCP1_pin, OUTPUT);
attachInterrupt(digitalPinToInterrupt(3), shaft_moved, LOW);
attachInterrupt(digitalPinToInterrupt(2), reset_to_0, FALLING);
pinMode(2,INPUT_PULLUP);
pinMode(DT_pin,INPUT);
}
void loop() {
DisplayDigit(counter);
}
Comments