Menús de Arduino fácil de codificador rotatorio (2 / 3 paso)

Paso 2: código

Este es el código. Mirando la estructura y los comentarios espero que usted lo encontrará fácil de adaptar a sus necesidades!

 /*******Interrupt-based Rotary Encoder Menu Sketch******* * by Simon Merrett, based on insight from Oleg Mazurov, Nick Gammon, rt and Steve Spence, and code from Nick Gammon * 3,638 bytes with debugging on UNO, 1,604 bytes without debugging */ // Rotary encoder declarations static int pinA = 2; // Our first hardware interrupt pin is digital pin 2 static int pinB = 3; // Our second hardware interrupt pin is digital pin 3 volatile byte aFlag = 0; // let's us know when we're expecting a rising edge on pinA to signal that the encoder has arrived at a detent volatile byte bFlag = 0; // let's us know when we're expecting a rising edge on pinB to signal that the encoder has arrived at a detent (opposite direction to when aFlag is set) volatile byte encoderPos = 0; //this variable stores our current value of encoder position. Change to int or uin16_t instead of byte if you want to record a larger range than 0-255 volatile byte oldEncPos = 0; //stores the last encoder position value so we can compare to the current reading and see if it has changed (so we know when to print to the serial monitor) volatile byte reading = 0; //somewhere to store the direct values we read from our interrupt pins before checking to see if we have moved a whole detent // Button reading, including debounce without delay function declarations const byte buttonPin = 4; // this is the Arduino pin we are connecting the push button to byte oldButtonState = HIGH; // assume switch open because of pull-up resistor const unsigned long debounceTime = 10; // milliseconds unsigned long buttonPressTime; // when the switch last changed state boolean buttonPressed = 0; // a flag variable // Menu and submenu/setting declarations byte Mode = 0; // This is which menu mode we are in at any given time (top level or one of the submenus) const byte modeMax = 3; // This is the number of submenus/settings you want byte setting1 = 0; // a variable which holds the value we set byte setting2 = 0; // a variable which holds the value we set byte setting3 = 0; // a variable which holds the value we set /* Note: you may wish to change settingN etc to int, float or boolean to suit your application. Remember to change "void setAdmin(byte name,*BYTE* setting)" to match and probably add some "modeMax"-type overflow code in the "if(Mode == N && buttonPressed)" section*/ void setup() { //Rotary encoder section of setup pinMode(pinA, INPUT_PULLUP); // set pinA as an input, pulled HIGH to the logic voltage (5V or 3.3V for most cases) pinMode(pinB, INPUT_PULLUP); // set pinB as an input, pulled HIGH to the logic voltage (5V or 3.3V for most cases) attachInterrupt(0,PinA,RISING); // set an interrupt on PinA, looking for a rising edge signal and executing the "PinA" Interrupt Service Routine (below) attachInterrupt(1,PinB,RISING); // set an interrupt on PinB, looking for a rising edge signal and executing the "PinB" Interrupt Service Routine (below) // button section of setup pinMode (buttonPin, INPUT_PULLUP); // setup the button pin // DEBUGGING section of setup Serial.begin(9600); // DEBUGGING: opens serial port, sets data rate to 9600 bps } void loop() { rotaryMenu(); // carry out other loop code here } void rotaryMenu() { //This handles the bulk of the menu functions without needing to install/include/compile a menu library //DEBUGGING: Rotary encoder update display if turned if(oldEncPos != encoderPos) { // DEBUGGING Serial.println(encoderPos);// DEBUGGING. Sometimes the serial monitor may show a value just outside modeMax due to this function. The menu shouldn't be affected. oldEncPos = encoderPos;// DEBUGGING }// DEBUGGING // Button reading with non-delay() debounce - thank you Nick Gammon! byte buttonState = digitalRead (buttonPin); if (buttonState != oldButtonState){ if (millis () - buttonPressTime >= debounceTime){ // debounce buttonPressTime = millis (); // when we closed the switch oldButtonState = buttonState; // remember for next time if (buttonState == LOW){ Serial.println ("Button closed"); // DEBUGGING: print that button has been closed buttonPressed = 1; } else { Serial.println ("Button opened"); // DEBUGGING: print that button has been opened buttonPressed = 0; } } // end if debounce time up } // end of state change //Main menu section if (Mode == 0) { if (encoderPos > (modeMax+10)) encoderPos = modeMax; // check we haven't gone out of bounds below 0 and correct if we have else if (encoderPos > modeMax) encoderPos = 0; // check we haven't gone out of bounds above modeMax and correct if we have if (buttonPressed){ Mode = encoderPos; // set the Mode to the current value of input if button has been pressed Serial.print("Mode selected: "); //DEBUGGING: print which mode has been selected Serial.println(Mode); //DEBUGGING: print which mode has been selected buttonPressed = 0; // reset the button status so one press results in one action if (Mode == 1) { Serial.println("Mode 1"); //DEBUGGING: print which mode has been selected encoderPos = setting1; // start adjusting Vout from last set point } if (Mode == 2) { Serial.println("Mode 2"); //DEBUGGING: print which mode has been selected encoderPos = setting2; // start adjusting Imax from last set point } if (Mode == 3) { Serial.println("Mode 3"); //DEBUGGING: print which mode has been selected encoderPos = setting3; // start adjusting Vmin from last set point } } } if (Mode == 1 && buttonPressed) { setting1 = encoderPos; // record whatever value your encoder has been turned to, to setting 3 setAdmin(1,setting1); //code to do other things with setting1 here, perhaps update display } if (Mode == 2 && buttonPressed) { setting2 = encoderPos; // record whatever value your encoder has been turned to, to setting 2 setAdmin(2,setting2); //code to do other things with setting2 here, perhaps update display } if (Mode == 3 && buttonPressed){ setting3 = encoderPos; // record whatever value your encoder has been turned to, to setting 3 setAdmin(3,setting3); //code to do other things with setting3 here, perhaps update display } } // Carry out common activities each time a setting is changed void setAdmin(byte name, byte setting){ Serial.print("Setting "); //DEBUGGING Serial.print(name); //DEBUGGING Serial.print(" = "); //DEBUGGING Serial.println(setting);//DEBUGGING encoderPos = 0; // reorientate the menu index - optional as we have overflow check code elsewhere buttonPressed = 0; // reset the button status so one press results in one action Mode = 0; // go back to top level of menu, now that we've set values Serial.println("Main Menu"); //DEBUGGING } //Rotary encoder interrupt service routine for one encoder pin void PinA(){ cli(); //stop interrupts happening before we read pin values reading = PIND & 0xC; // read all eight pin values then strip away all but pinA and pinB's values if(reading == B00001100 && aFlag) { //check that we have both pins at detent (HIGH) and that we are expecting detent on this pin's rising edge encoderPos --; //decrement the encoder's position count bFlag = 0; //reset flags for the next turn aFlag = 0; //reset flags for the next turn } else if (reading == B00000100) bFlag = 1; //signal that we're expecting pinB to signal the transition to detent from free rotation sei(); //restart interrupts } //Rotary encoder interrupt service routine for the other encoder pin void PinB(){ cli(); //stop interrupts happening before we read pin values reading = PIND & 0xC; //read all eight pin values then strip away all but pinA and pinB's values if (reading == B00001100 && bFlag) { //check that we have both pins at detent (HIGH) and that we are expecting detent on this pin's rising edge encoderPos ++; //increment the encoder's position count bFlag = 0; //reset flags for the next turn aFlag = 0; //reset flags for the next turn } else if (reading == B00001000) aFlag = 1; //signal that we're expecting pinA to signal the transition to detent from free rotation sei(); //restart interrupts } // end of sketch! 

He utilizado "Depuración" al inicio de cada comentario en cualquier línea que no es crítico para el menú para hacer su cosa. Si estás contento con la función de menú, puede comentar o borrar estas líneas de tamaño más pequeño bosquejo compilado.

Tenga en cuenta que una parte clave de la navegación del menú es retroalimentación al usuario mientras que ellos son desplazarse a través de la opción y la configuración. Por lo tanto, si decide no incluir las líneas de depuración, probablemente debería utilizar otro indicador visual (por ejemplo texto pantalla LCD, LED) que entradas de codificador son navegar por el menú y cambiar la configuración.

Si yo comente las líneas de depuración (teniendo en cuenta que algunos comentarios visuales todavía sería necesaria para la navegación del menú) el código compilado es alrededor de 1.650 bytes para el Arduino Uno, ojala dejar mucho espacio en su ATMEGA328P para las partes más emocionantes del boceto!

Vaya al paso 3 para saber cómo funciona el sistema de menú.

Artículos Relacionados

Mejorada lectura de codificador rotatorio de Arduino

Mejorada lectura de codificador rotatorio de Arduino

Codificadores rotativos grandes dispositivos de entrada para proyectos de electrónica - ojala este Instructable inspirará y ayudarle a utilizar en su próximo proyecto.¿Por qué escribir código de codificador rotatorio?Quería usar un codificador rotato
Arduino Nano y Visuino: Control de servos con codificador rotatorio

Arduino Nano y Visuino: Control de servos con codificador rotatorio

Hay un montón de Instructables que Servo control con potenciómetro, sin embargo a veces es útil controlar con un Codificador rotatorio. En este Instructable, les mostraré lo fácil que es implementar esto con la ayuda de Visuino - un ambiente de desar
Arduino Nano: Codificador rotatorio con Visuino

Arduino Nano: Codificador rotatorio con Visuino

Los codificadores rotativos son sensores de rotación exacto muy útiles, también de uso frecuente como usuario control dispositivos de entrada en lugar de potenciómetros. Son fáciles de conectar al Arduino, y con la ayuda de Visuino - un ambiente de d
Arduino Nano y Visuino: Control de Motor paso a paso con codificador rotatorio

Arduino Nano y Visuino: Control de Motor paso a paso con codificador rotatorio

A veces es necesario tener un Motor de pasos seguir la rotación de un Codificador rotatorio para posicionamiento preciso. Yo he estado planeando Instructable sobre este por un tiempo, pero finalmente el par de días después otra pregunta del usuario V
Diseñar un menú personalizado menú sistema--Android/Arduino para principiantes--absolutamente ninguna programación requerida

Diseñar un menú personalizado menú sistema--Android/Arduino para principiantes--absolutamente ninguna programación requerida

IntroducciónEste instructable muestra cómo utilizar el libre pfodDesigner disponible en GooglePlay para diseñar un sistema Android menú con submenús para dispositivos compatibles con Arduino.El tutorial es adecuado para principiantes. No se requiere
Arduino - codificador rotatorio Simple ejemplo KY-040

Arduino - codificador rotatorio Simple ejemplo KY-040

¡Hola mundo! Este es un ejemplo de cómo usar el codificador rotatorio de KY-040.Su forma muy básica pero si su nuevo a arduino o no pudo encontrar ningún código, entonces tienes algo para comenzar con.porque hay poca documentación sobre el kit de sen
ESP8266 y Visuino: Control Servo remotamente sobre Wi-Fi con codificador rotatorio

ESP8266 y Visuino: Control Servo remotamente sobre Wi-Fi con codificador rotatorio

Módulos de ESP8266 son controladores de bajo costo independiente gran con construido en Wi-Fi. En este Instructable mostrará cómo puede controlar un Servo remotamente sobre Wi-Fi con un codificador rotatorio. El Instructable es una versión similar pe
Codificador rotatorio tira LED brillo controlador

Codificador rotatorio tira LED brillo controlador

Simplemente tira brillo controlador de LED con rotary encoder y attiny microcontrolador 85Paso 1: Introducción:Le mostrará cómo controlar fácilmente el brillo de la tira LED. Este es realmente un controlador PWM. Está diseñado sólo para DC. Olvidar C
Ejemplo de codificador rotatorio de RGB (ATmega328, AVR)

Ejemplo de codificador rotatorio de RGB (ATmega328, AVR)

las anterior configuración utiliza interrupción servicio rutinas (ISRs) para interpretar un codificador rotatorio.  El codificador rotatorio específico utilizado también contiene un LED RGB, que es conducido por PWM.  Hay un video en el artículo comp
ESP8266 Wifi adiciónales para Arduino fácil

ESP8266 Wifi adiciónales para Arduino fácil

ActualizaciónEl proceso descrito aquí ya no se recomienda. Este instructivo ha sido reemplazado por ESP8266 WiFi Shield para Arduino y otros micros que proporciona una función de configuración de página web más universal.IntroducciónESP8266 es un chi
BRICOLAJE | Sistema de seguridad de Arduino fácil láser Tripwire!

BRICOLAJE | Sistema de seguridad de Arduino fácil láser Tripwire!

En este tutorial enseñará usted cómo usted puede construir su propio sistema de seguridad de Tripwire de láser en casa!Usted necesitará los siguientes componentes y materiales:Luz de LEDMódulo del laserMódulo de Sensor láserAltavoz o zumbador piezoel
Centinela de arduino fácil

Centinela de arduino fácil

Este instructable le mostrará cómo hacer un fácil centinela de bajo costo.Paso 1: partesPara este proyecto necesitas:-un protoboard-7 cables de puente (macho)-Arduino Uno-HC-SR04 sensor ultrasónico-Servo sg90-Pistola elásticoPaso 2: Cableado / constr
Luz de Arduino fácil tras Robot

Luz de Arduino fácil tras Robot

Este es un tutorial sobre cómo hacer un robot siguiente luz usando Arduino, se ha simplificado para que los principiantes pueden intentar este proyecto también. Este proyecto sólo debe tomar en más de una hora. Espero que lo disfruten.Paso 1: materia
Interface MP3 para Arduino: fácil y barato

Interface MP3 para Arduino: fácil y barato

he añadido una continuación a este Instructable:La continuación muestra cómo diseñar, grabar y construir un escudo de PCB para conectar el MP3 al Arduino. Reemplaza los conmutadores analógicos con un 74HC244. Tablero de una sola capa con diseño de co