Close
0%
0%

Polling a Push Button Rotary Encoder

A push button rotary encoder is a neat input device for an Arduino.
Unfortunately interfacing to it is not!

Similar projects worth following
Here is my solution to using push button rotary encoder on the Arduino (Nano).

What is polling?

If you have uploaded the example "Blink without delay" sketch then you have used polling:

// Blink without delay
void setup() {
  pinMode(LED_BUILTIN,OUTPUT);
  digitalWrite(LED_BUILTIN,LOW);
}
void loop() {
  static unsigned long previousMillis=0;
  unsigned long intervalMillis=1000;
  unsigned long currentMillis;
  // Toggle LED when time interval is up!
  currentMillis=millis();
  if (currentMillis-previousMillis>=intervalMillis) {
    previousMillis = currentMillis;
    digitalWrite(LED_BUILTIN,!digitalRead(LED_BUILTIN));
  }
}

 
Polling just checks your input switches regularly to determine if something has changed. In the "Blink without delay" example, the millis counter is polled until one second (i.e. 1000ms) has passed. At this time the LED state is inverted (i.e. toggled).
The Ticker library does this more succinctly:

#include "Ticker.h"
// The Blink routine
void Blink() {
  digitalWrite(LED_BUILTIN,!digitalRead(LED_BUILTIN));
}
// Create a timer
Ticker timer1;
void setup() {
  pinMode(LED_BUILTIN, OUTPUT); // Initialise the Ticker
  timer1.setCallback(Blink);    // Set timer1 function to Blink()
  timer1.setInterval(1000);     // Set timer1 interval to 1000 ms
  // start the Ticker
  timer1.start();
}
void loop() {
  // Update the Ticker
  timer1.update();
}

 With the Ticker example a "timer" (i.e. a Ticker) has been set up to toggle the LED every 1000ms.

Not polling but an interrupt service routine

Another way is to use a real timer and an interrupt service routine (ISR):

volatile unsigned int magic=0;
ISR(TIMER2_OVF_vect) {
  static unsigned int phase=0;
  if (phase<0x8000) {
    phase+=magic;
    if (phase>=0x8000) {
      digitalWrite(LED_BUILTIN,LOW);  // LED on
    }
  } else {
    phase+=magic;
    if (phase<0x8000) {
      digitalWrite(LED_BUILTIN,HIGH); // LED off
    }
  }
}
void setup() {
  // LED pinMode(LED_BUILTIN,OUTPUT);
  // Use Timer 2 for ISR
  // Good for ATmega48A/PA/88A/PA/168A/PA/328/P
  cli();
  TIMSK2=0;                                  // Clear timer interrupts
  TCCR2A=(0<<COM2A0)|(0<<COM2B0)|(3<<WGM20); // Fast PWM
  TCCR2B=(1<<WGM22)|(2<<CS20);               // 2 MHz clock and (Mode 7)
  OCR2A=243;                                 // Set for 8197 Hz
  OCR2B=121;                                 // Not used
  TIMSK2=(1<<TOIE2)|(0<<OCIE2A)|(0<<OCIE2B); // Set interrupts
  sei();
  // Update frequency without interrupt
  // Note freq should be between 1 and 4095
  unsigned int freq=1;                     
  cli();
  // magic=(freq<<3); // magic=freq/8
  magic=4; // 0.5Hz
  sei();
}
void loop() {
}

Now the ISR was truely awful as far as readable code! And I had to use a timer. The above code came from my Midi project. The timer frequency is programmable over a wide range and thus a bit more complicated than usual.

A better way to use timers and interrupts is to use a library like TimerOne:

#include <TimerOne.h>

void setup(void) {
  pinMode(LED_BUILTIN,OUTPUT);
  Timer1.initialize(1000000); // 1s
  Timer1.attachInterrupt(Blink);
  Serial.begin(9600);
  delay(200);
  Serial.println(TIMSK0,BIN);
}

void Blink(void)
{
  digitalWrite(LED_BUILTIN,!digitalRead(LED_BUILTIN));
}
void loop(void) {

}

 Here the timer "polling" period is programmable in microseconds (except the accuarcy is probably 2-4us.

A free ride!

Why not use the millis timer (i.e. timer0)?

Checking the interrupt timer register, I find only the overflow interrupt (TOIE0) has been used. This leaves OCIE0B and OCIE0A free for use (subject to being mindful of the millis ISR execution time requirements and not using PWM on pins 5 and 6).

Notes:

  • Timer0 is an 8 bit timer and the prescaler is 1/64 (i.e. the clock is 250kHz).
  • The overflow count is 255 so the timer interrupt interval is 1024us, not 1000us.

We can create a custom millis and seconds timer as shown below:

// Custom Clock ISR
volatile unsigned long clockTics=0;
ISR(TIMER0_COMPA_vect) {
  static long clockMillis=...
Read more »

text/x-arduino - 7.96 kB - 02/04/2018 at 00:28

Download

Adobe Portable Document Format - 670.94 kB - 01/26/2018 at 10:05

Preview
Download

Adobe Portable Document Format - 459.97 kB - 01/26/2018 at 10:05

Preview
Download

Adobe Portable Document Format - 85.09 kB - 01/26/2018 at 10:05

Preview
Download

JPEG Image - 109.21 kB - 01/26/2018 at 10:05

Preview
Download

View all 6 files

  • Rotary Encoder Blink

    agp.cooper02/04/2018 at 00:27 0 comments

    Rotary Encoder Blink

    Final log.

    I have stripped the code down and wriiten a programmable Blink sketch.

    It is still a complicated beast but that is the way it is:

    /* 
      Rotary Encoder Blink
      ====================
      Written by Alan Cooper (agp.cooper@gmail.com)
      This work is licensed under the 
      Creative Commons Attribution - Non Commercial 2.5 License.
      This means you are free to copy and share the code (but not to sell it).
      Also it is good karma to attribute the source of the code.
    */
    
    /*
      ROTARY ENCODER AND PUSH BUTTON POLLING CODE
        Uses Timer0 without upsetting millis(), delay() etc.
        You lose PWM on Arduino/Nano pin 5 (D5).
        Don't turn the encoder too fast as it will not work!
    */
    #define PinA 5
    #define PinB 4
    #define SW   3
    volatile bool UpdateSwitch=false;
    volatile byte Switch=HIGH;
    volatile int EncoderPos=0;
    ISR(TIMER0_COMPB_vect) {
      static byte testPinA=(PIND>>PinA)&1;
      static byte testPinB=(PIND>>PinB)&1;
      static byte lastPinA=LOW;
      static byte lastPinB=LOW;
      static bool flagPinA=false;
      static bool flagPinB=false;
      static bool encoderFlag=true;
      static int encoderDir=0;
      static byte testSW=HIGH;
      static byte statusSW=HIGH;
      static byte cntSW=0;  
      
      // Update Encoder Position
      lastPinA=testPinA;             // Save PinA
      lastPinB=testPinB;             // Save PinB
      testPinA=(PIND>>PinA)&1;       // Get PinA
      testPinB=(PIND>>PinB)&1;       // Get PinB
      
      /* If your encoder jumps in steps of two, uncomment this code */
      // if ((testPinA==HIGH)&&(testPinB==HIGH)) encoderFlag=true; // Encoder is in detent
      // if ((testPinA==LOW)&&(testPinB==LOW)) encoderFlag=false;  // Encoder is between detents
      
      if (encoderFlag) {             // First transition (leaving detent) only
        if (testPinA!=lastPinA) {    // Change in PinA?
          flagPinA=true;             // Flag PinA has changed
          encoderDir=-1;             // Assume it is the last flag to change
        }
        if (testPinB!=lastPinB) {    // Change in PinB?
          flagPinB=true;             // Flag PinB has changed
          encoderDir=1;              // Assume it is the last flag to change
        }
        if (flagPinA&&flagPinB) {    // Both flags have changed
          EncoderPos+=encoderDir;
          flagPinA=false;            // Reset PinA flag
          flagPinB=false;            // Reset PinB flag
        }
      }
      
      // Update switch with 10 ms debounce
      testSW=(PIND>>SW)&1;
      if (testSW!=statusSW) {
        encoderFlag=true;            // Reset encoder flag (precaution)
        statusSW=testSW;
        cntSW=10;
      }
      if (cntSW>0) {
        cntSW--;
        if (cntSW==0) {
          Switch=statusSW;
          UpdateSwitch=true;
        }
      }
    }
    
    
    /* MENU SET UP */
    enum NoYes {N,Y};
    enum MenuLevel {Top,Menu,Set};
    enum MenuItem      { Exit_Menu  , Delay_MS  };
    char* menuName[]  ={"Exit Menu ","Delay ms "};
    char menuNumeric[]={         N  ,        Y  };
    int menuValue[]   ={         Y  ,      500  };
    int menuValueMin[]={         N  ,        1  };
    int menuValueMax[]={         Y  ,    32766  };
    int menuSize=sizeof(menuName)/sizeof(char*);
    int menuLevel=Menu;
    
    // Our variable to set the delay period
    unsigned long intervalMillis=1000;
    
    bool processMenu(void) {
      static int lastPos=Exit_Menu;
      static int lastMenuLevel=Top;
      
      // Disable polling
      TIMSK0&=~(1<<OCIE0B);
      
      // Pre-empt menu level display 
      if (menuLevel!=lastMenuLevel) {
        lastMenuLevel=menuLevel;
        if (menuLevel==Menu) {
          Serial.print("Menu: ");
          Serial.print(menuName[EncoderPos]);
          if (menuNumeric[EncoderPos]==Y) {
            Serial.println(menuValue[EncoderPos]);
          } else {       
            if (menuValue[EncoderPos]==N) {
              Serial.println("N");      
            } else {
              Serial.println("Y");      
            }
          }          
        } else if (menuLevel==Set) {
          Serial.print("Set:  ");
          Serial.print(menuName[lastPos]);
          if (menuNumeric[lastPos]==Y) {
            Serial.println(menuValue[lastPos]);
          } else {       
            if (menuValue[lastPos]==N) {
              Serial.println("N");      
            } else {
              Serial.println("Y");      
            }
          }      
        } else {
          // How did you get here?      
        }
      }
      
      // If push button pushed toggle menu level
      if (UpdateSwitch) {
        UpdateSwitch=false;
        if (Switch==LOW) {
          // Re-enter menu if button pushed (for long enough)
          if (menuLevel==Top) {
            menuLevel=Menu;
            lastMenuLevel=Top;                         
            lastPos=Exit_Menu;                               
            EncoderPos=Exit_Menu;
            menuValue[Exit_Menu]=Y;
          } else {
            // Toggle menu level
            if (menuLevel==Menu) {
              menuLevel=Set;
            } else {
              menuLevel=Menu;
            }
            if (menuLevel==Menu) {
              //...
    Read more »

  • Still Testing II

    agp.cooper02/03/2018 at 06:18 0 comments

    Still Testing II

    A bit of code clean up!

    Used enum types rather and constants as this makes changing the menu easier:

    enum NoYes {N,Y};
    enum MenuLevel {Top,Menu,Set};
    enum MenuItem      { Exit_Menu  , Year  , Month  , Day  , Hour  , Minute  , Second  , Use_Time ,  Local_Hour  , Local_Min  , Use_UT  , Sample_Min  , Upload_Data  };
    char* menuName[]  ={"Exit Menu ","Year ","Month ","Day ","Hour ","Minute ","Second ","Use Time ","Local Hour ","Local Min ","Use UT ","Sample Min ","Upload Data "};
    int menuValue[]   ={          Y ,  2000 ,      1 ,    1 ,     0 ,       0 ,       0 ,         Y ,           8 ,          0 ,       Y ,           1 ,            Y };
    char menuNumeric[]={          N ,     Y ,      Y ,    Y ,     Y ,       Y ,       Y ,         N ,           Y ,          Y ,       N ,           Y ,            N };
    int menuValueMin[]={          N ,  1970 ,      1 ,    1 ,     0 ,       0 ,       0 ,         N ,         -12 ,        -59 ,       N ,           1 ,            N };
    int menuValueMax[]={          Y ,  2100 ,     12 ,   31 ,    23 ,      59 ,      59 ,         Y ,          12 ,         59 ,       Y ,        1440 ,            Y };
    int menuSize=sizeof(menuName)/sizeof(char*);
    int menuLevel=Menu;
    

    The menu set up is very clear to read and easy to modify. Just stay linear in your menu layout!

    Reworked the polling ISR to take the guess work out of detent status of the rotary encoder:

      // Update Encoder Position
      lastPinA=testPinA;             // Save PinA
      lastPinB=testPinB;             // Save PinB
      testPinA=(PIND>>PinA)&1;       // Get PinA
      testPinB=(PIND>>PinB)&1;       // Get PinB
      
      // This rotary encoder updates twice per detent!
      if ((testPinA==HIGH)&&(testPinB==HIGH)) encoderFlag=true; // Encoder is in detent
      if ((testPinA==LOW)&&(testPinB==LOW)) encoderFlag=false;  // Encoder is between detents
      if (encoderFlag) {                                        // First transition (leaving detent) only
        if (testPinA!=lastPinA) {      // Change in PinA?
          flagPinA=true;               // Flag PinA has changed
          encoderDir=-1;               // Assume it is the last flag to change
        }
        if (testPinB!=lastPinB) {      // Change in PinB?
          flagPinB=true;               // Flag PinB has changed
          encoderDir=1;                // Assume it is the last flag to change
        }
        if (flagPinA&&flagPinB) {      // Both flags have changed
          EncoderPos+=encoderDir;
          flagPinA=false;              // Reset PinA flag
          flagPinB=false;              // Reset PinB flag
        }
      }
    

    NOTE: YOUR ROTARY ENCODER MAY BE DIFFERENT! You can comment out these two lines:

      // This rotary encoder updates twice per detent!
      if ((testPinA==HIGH)&&(testPinB==HIGH)) encoderFlag=true; // Encoder is in detent
      if ((testPinA==LOW)&&(testPinB==LOW)) encoderFlag=false;  // Encoder is between detents

    Disabled polling during menu processing.

    Reworked the start up for a local time at start up with a menu option for Universal Time (UT).

    The code is long but not much I can do to reduce this (other than hide it in an include file):

    /* 
      Universal Time Clock with Periodic Sampler
      ==========================================
      Written by Alan Cooper (agp.cooper@gmail.com)
      This work is licensed under the 
      Creative Commons Attribution - Non Commercial 2.5 License.
      This means you are free to copy and share the code (but not to sell it).
      Also it is good karma to attribute the source of the code.
    */
    
    // Compile and upload time adjustment (secs)
    #define UploadTime 11
    
    // Analog read on A7
    #define Sensor A7
     
    // Need the Wire library for RTC and AT24C32
    #include <Wire.h>
    
    // Use RTC library
    #include "RTClib.h"
    RTC_DS1307 rtc;
    
    // Use AT24Cxx library
    #include <AT24Cxx.h>
    AT24Cxx AT24C32(0x50);
    
    // Useful union/structures to read/write A  if (LEDTimer==-1) LEDTimer=menuValue[LED_Timeout];T24C32 data
    union {
      struct{
        char Year;
        char Month;
        char Day;
        char Hour;
        char Minute;
        char Second;
        int Value;
      };
      char data[8]; 
    } AT24C32_Slot;
    union {
      struct{
        int Value;
      };
      char data[2]; 
    } AT24C32_Int;
      
    // Use LCD library
    #include <LiquidCrystal.h>
    #define en   7
    #define rs   8
    #define d4   9
    #define d5  10
    #define d6  11
    #define d7  12
    #define led 13
    LiquidCrystal lcd(rs,en,d4,d5,d6,d7);
    
    /* ROTARY ENCODER AND PUSH BUTTON POLLING CODE */
    #define PinA 2
    #define PinB 3
    #define SW   4
    volatile bool UpdateSwitch=false;
    volatile byte Switch=HIGH;
    volatile int EncoderPos=0;
    ISR(TIMER0_COMPB_vect) {
      static byte testPinA=(PIND>>PinA)&...
    Read more »

  • Still Testing

    agp.cooper02/02/2018 at 13:28 0 comments

    Still Testing

    Those rotary encoders are still causing trouble, occasionally they get confused. I can't work out why but t must be a memory clash or an interrupt problem. I am using volatile variable without turning off interrupts so I should look at that first. But once it gets confused it stays that way (more likely a memory clash).

    I have added a sampling and datalogging code using the RTC AT24C32 EEPROM. Why not, its come for free with the RTC I got. At the moment the sampler just records a random number that can be downloaded to the serial port:

    /* 
     * Universal Time Clock with Periodic Sampler 
     */
    #include <Wire.h>
    #include "RTClib.h"
    RTC_DS1307 rtc;
    
    #include <AT24Cxx.h>
    AT24Cxx AT24C32(0x50); 
    // An anonymous union/structure to read/write RTC AT24C32 data
    union {
      struct{
        char Year;
        char Month;
        char Day;
        char Hour;
        char Minute;
        char Second;
        int Value;
      };
      char data[8]; 
    } AT24C32_Slot;
    union {
      struct{
        int Value;
      };
      char data[2]; 
    } AT24C32_Int;
      
    // Include LCD library and initialise
    #include <LiquidCrystal.h>
    // Define Adruino pin numbers for LCD
    #define en   7
    #define rs   8
    #define d4   9
    #define d5  10
    #define d6  11
    #define d7  12
    #define led 13
    // Set LCD
    LiquidCrystal lcd(rs,en,d4,d5,d6,d7);
    
    /* ROTARY ENCODER AND PUSH BUTTON POLLING CODE */
    #define PinA 3
    #define PinB 2
    #define SW   4
    volatile bool UpdateSwitch=false;
    volatile byte Switch=HIGH;
    volatile int EncoderPos=0;
    ISR(TIMER0_COMPB_vect) {
      static byte testPinA=(PIND>>PinA)&1;
      static byte testPinB=(PIND>>PinB)&1;
      static byte lastPinA=LOW;
      static byte lastPinB=LOW;
      static bool flagPinA=false;
      static bool flagPinB=false;
      static bool encoderFlag=true;
      static int encoderDir=0;
      static byte testSW=HIGH;
      static byte statusSW=HIGH;
      static byte cntSW=0;  
      
      // Update Encoder Position
      lastPinA=testPinA;             // Save PinA
      lastPinB=testPinB;             // Save PinB
      testPinA=(PIND>>PinA)&1;       // Get PinA
      testPinB=(PIND>>PinB)&1;       // Get PinB
      if (testPinA!=lastPinA) {      // Change in PinA?
        flagPinA=true;               // Flag PinA has changed
        encoderDir=-1;               // Assume it is the last flag to change
      }
      if (testPinB!=lastPinB) {      // Change in PinB?
        flagPinB=true;               // Flag PinB has changed
        encoderDir=1;                // Assume it is the last flag to change
      }
      if (flagPinA&&flagPinB) {      // Both flags have changed
        // This rotary encoder updates twice per detent!
        if (encoderFlag) {           // First transition only
          EncoderPos+=encoderDir;
        }
        encoderFlag=(!encoderFlag);    
        flagPinA=false;              // Reset PinA flag
        flagPinB=false;              // Reset PinB flag
      }
      
      // Update switch with 10 ms debounce
      testSW=(PIND>>SW)&1;
      if (testSW!=statusSW) {
        encoderFlag=true;            // Reset encoder flag (precaution)
        statusSW=testSW;
        cntSW=10;
      }
      if (cntSW>0) {
        cntSW--;
        if (cntSW==0) {
          Switch=statusSW;
          UpdateSwitch=true;
        }
      }
    }
    
    
    /* MENU SET UP */
    char* menuName[]={
      "Exit Menu ",    //  0 - Exit menu system
      "UT Year ",      //  1
      "UT Month ",     //  2
      "UT Day ",       //  3
      "UT Hour ",      //  4
      "UT Minute ",    //  5
      "UT Second ",    //  6
      "UT Save ",      //  7
      "Local Hour ",   //  8
      "Local Min ",    //  9
      "Upload Sec ",   // 10
      "Sample Min ",   // 11 - Minutes between samples
      "Upload Data "   // 12 - Upload data to serial port 
    };
    int menuSize=sizeof(menuName)/sizeof(char*);
    int menuValue[]=   {  1,2000,  1,  1,  0,  0,  0,  0,  8,  0,  7,  6,  1};
    // Non-numeric values are 'N'=0 and 'Y'=1
    char menuNumeric[]={'N', 'Y','Y','Y','Y','Y','Y','N','Y','Y','Y','Y','N'};
    int menuValueMin[]={  0,1000,  1,  1,  0,  0,  0,  0,-59,  0,  0,  0};
    int menuValueMax[]={  1,2999, 12, 31, 23, 59, 59,  1, 59, 59, 60,  1};
    int menuLevel=0;
    
    // AT24C32 usage
    char settings[8];              // 32752-32759
    unsigned int sampleSlot=0; // Slot 0 to 4093 (2 Slots reserved)
    
    bool processMenu(void) {
      static int lastPos=0;
      static int lastMenuLevel=-1;
    
      // Pre-empt menu level display 
      if (menuLevel!=lastMenuLevel) {
        lastMenuLevel=menuLevel;
        lcd.clear();
        lcd.setCursor(0,0);
        if (menuLevel==0) {
          lcd.print("Menu:");
          lcd.setCursor(0,1);
          lcd.print(menuName[EncoderPos]);
          if (menuNumeric[EncoderPos]=='Y') {
            lcd.print(menuValue[EncoderPos]);
          } else...
    Read more »

  • Front Panel

    agp.cooper02/01/2018 at 12:28 0 comments

    Front Panel

    The front panel did not go very smoothly despite the effort in setting it up. To ensure I did not waste my supply of Birch plywood I just made a prototype of the front panel with some fiberboard.

    I forgot the LCD window on the first front panel!, even so it demonstrated that the Keyes rotary encoder was a bad choice. The encoder shaft collar has no thread and the two bolt holes on the PCB are on one side of the shaft. The encoder moves to the side when pressed. Other than gluing the encoder to the back of the front panel it is not going to work.

    Made a second front panel (with an LCD window) for a bare rotary encoder. Made up a small strip board with legs for the rotary encoder to fit level with the LCD display :

    The Nano sockets were removed and the Nano was soldered directly to the stripboard as it was no going to fit (in the image above, the red led thing under the rotay switch).

    The RTC sockets will need to go as well.

    Testing

    At first the rotation increment/decrement was the wrong way. No problem I have swapped the A and B pins on the rotatry encoder. I fixed it in software for now and will rewire it later.

    The main problem was that the menu and setting increments and decrements in steps of two? This puzzled me for a while until I realised it could only be the rotary encoder. Sure enough if you rotate the encode 1/2 a detent if increments once and then again at the detent. It reliably does this so the double increment is by design! How stupid! To fix I added a flag to the polling routine to only update the second increment (at detent).

    It now work fine, upon boot up:

    The menu (item) after one press (for about a second):

    This is the Menu Item on the first line and the current setting on the second line (n.b. "X" means abort all changes while "Y" means accept and "N" means cancel this Menu Item.

    Second press to change or set the menu item:

    This Set Menu allows you to change a setting.

    And a third press to accept the setting which in this case "X" will return you to the UT Clock (with no changes to the clock settings).

    The location of the rotary encoder ideal for a right hander as it keeps your fingers from blocking your view of the LCD while rotating the knob.

    Now the only problem I noticed was that the day number is wrong! Which means the timeSpan() does not like negative numbers. Fixed, don't use timeSpan()!

    Updated Code

    Here is the updated code. Note this code is configured for my stupid rotary encoder!

    // Include RTC libraries and initialise
    #include <Wire.h>
    #include "RTClib.h"
    RTC_DS1307 rtc;
    
    // Include LCD library and initialise
    #include <LiquidCrystal.h>
    // Define Adruino pin numbers for LCD
    #define en   7
    #define rs   8
    #define d4   9
    #define d5  10
    #define d6  11
    #define d7  12
    #define led 13
    // Set LCD
    LiquidCrystal lcd(rs,en,d4,d5,d6,d7);
    
    /* ROTARY ENCODER AND PUSH BUTTON POLLING CODE */
    #define Clk 3
    #define DT  2
    #define SW  4
    // Poll and debounces a Keyes rotary and push button switch
    // Inputs:
    //   Clk (Pin A without a pullup resistor)
    //   DT  (Pin B without a pullup resistor)
    //   SW  (Switch without a pullup resistor)
    // Exports:
    //   UpdateSwitch (bool)
    //   Switch [LOW|HIGH]
    //   EncoderPos (int)
    volatile bool UpdateSwitch=false;
    volatile byte Switch=HIGH;
    volatile int EncoderPos=0;
    volatile bool EncoderFlag=true;
    ISR(TIMER0_COMPB_vect) {
      static byte testClk=(PIND>>Clk)&1;
      static byte testDT=(PIND>>DT)&1;
      static byte lastClk=LOW;
      static byte lastDT=LOW;
      static bool flagClk=false;
      static bool flagDT=false;
      static int encoderDir=0;
      static byte testSW=HIGH;
      static byte statusSW=HIGH;
      static byte cntSW=0;  
      
      
      // Update Encoder Position
      lastClk=testClk;             // Save Clk
      lastDT=testDT;               // Save DT
      testClk=(PIND>>Clk)&1;       // Get Clk
      testDT=(PIND>>DT)&1;         // Get DT
      if (testClk!=lastClk) {      // Change in Clk?
        flagClk=true;              // Flag Clk has changed
        encoderDir=-1;             // Assume it is the last flag to change
      }
      if (testDT!=lastDT) {        // Change in DT?
        flagDT=true;               // Flag DT has changed
     encoderDir=...
    Read more »

  • UT Clock with Menu

    agp.cooper01/30/2018 at 09:07 0 comments

    UT Clock with Menu

    Added the menu system to the UT Clock. Had to add an abort/cancel option (i.e. 'X') to the "Done" menu option. An obvious omission.

    Here is the code:

    // Include RTC libraries and initialise
    #include <Wire.h>
    #include "RTClib.h"
    RTC_DS1307 rtc;
    
    // Include LCD library and initialise
    #include <LiquidCrystal.h>
    // Define Adruino pin numbers for LCD
    #define en   7
    #define rs   8
    #define d4   9
    #define d5  10
    #define d6  11
    #define d7  12
    #define led 13
    // Set LCD
    LiquidCrystal lcd(rs,en,d4,d5,d6,d7);
    
    /* ROTARY ENCODER AND PUSH BUTTON POLLING CODE */
    #define Clk 2
    #define DT  3
    #define SW  4
    // Poll and debounces a Keyes rotary and push button switch
    // Inputs:
    //   Clk (Pin A with 10k pullup resistor)
    //   DT  (Pin B with 10k pullup resistor)
    //   SW  (Switch without a pullup resistor)
    //   +   (Power for pullup resistors)
    //   Gnd
    // Exports:
    //   UpdateSwitch (bool)
    //   Switch [LOW|HIGH]
    //   EncoderPos (int)
    volatile bool UpdateSwitch=false;
    volatile byte Switch=HIGH;
    volatile int EncoderPos=0;
    ISR(TIMER0_COMPB_vect) {
      static byte testClk=(PIND>>Clk)&1;
      static byte testDT=(PIND>>DT)&1;
      static byte lastClk=LOW;
      static byte lastDT=LOW;
      static bool flagClk=false;
      static bool flagDT=false;
      static int encoderDir=0;
      static byte testSW=HIGH;
      static byte statusSW=HIGH;
      static byte cntSW=0;  
      
      // Update Encoder Position
      lastClk=testClk;            // Save Clk
      lastDT=testDT;              // Save DT
      testClk=(PIND>>Clk)&1;      // Get Clk
      testDT=(PIND>>DT)&1;        // Get DT
      if (testClk!=lastClk) {     // Change in Clk?
        flagClk=true;             // Flag Clk has changed
        encoderDir=-1;            // Assume it is the last flag to change
      }
      if (testDT!=lastDT) {       // Change in DT?
        flagDT=true;              // Flag DT has changed
        encoderDir=1;             // Assume it is the last flag to change
      }
      if (flagClk&&flagDT) {      // Both flags have changed
        EncoderPos+=encoderDir;   // Update the encoder
        flagClk=false;            // Reset Clk flag
        flagDT=false;             // Reset DT flag
      }
      
      // Update switch with 10ms debounce
      testSW=(PIND>>SW)&1;
      if (testSW!=statusSW) {
        statusSW=testSW;
        cntSW=10;
      }
      if (cntSW>0) {
        cntSW--;
        if (cntSW==0) {
          Switch=statusSW;
          UpdateSwitch=true;
        }
      }
    }
    
    
    /* MENU SET UP */
    char* menuName[]={"Done ","Year ","Month ","Day ","Hour ","Minute ","Second "};
    int menuSize=sizeof(menuName)/sizeof(char*);
    int menuValue[]=   {  1,  0,  1,  1,  0,  0,  0};
    char menuNumeric[]={'N','Y','Y','Y','Y','Y','Y'};
    int menuValueMin[]={  0,  0,  1,  1,  0,  0,  0};  // Non-numeric values 'N','X' and 'Y'
    int menuValueMax[]={  2,999, 12, 31, 23, 59, 59};
    int menuLevel=0;
    
    void setup() {
      // Initialise rotary encoder and push button
      pinMode(Clk,INPUT_PULLUP); // Rotary Clk
      pinMode(DT,INPUT_PULLUP);  // Rotary DT
      pinMode(SW,INPUT_PULLUP);  // Rotary SW
    
      // Turn on polling ISR
      OCR0B=0xA0;
      TIMSK0|=1<<OCIE0B;
    
      // Initialise LCD
      pinMode(led,OUTPUT);
      digitalWrite(led,HIGH);
      lcd.begin(16,2);
    
      // Print a message to the LCD.
      lcd.setCursor(0,0);lcd.print("Universal Time");
      // Check RTC
      if (!rtc.begin()) {
        lcd.setCursor(0,1);lcd.print("RTC not found");
        while (true);
      } else if (!rtc.isrunning()) {
        lcd.setCursor(0,1);lcd.print("RTC not running");
      } else {
        lcd.setCursor(0,1);lcd.print("RTC found");
      }
      
      // Set Universal Time based on Compile Time
      int localTimeHour=-8; // Perth Western Australia
      int localTimeMin=0;   // Perth Western Australia
      int uploadTimeSec=7;  // For my computer
    
      rtc.adjust(DateTime(F(__DATE__),F(__TIME__)));
      DateTime now=rtc.now();
      rtc.adjust(DateTime(now+TimeSpan(0,localTimeHour,localTimeMin,uploadTimeSec)));
      
      // Set menu to current time
      now=rtc.now();
      menuLevel=-1;              // Don't enter menu on start up
      menuValue[0]='X';          // Set "done" status to abort 
      menuValue[1]=now.year();
      menuValue[2]=now.month();
      menuValue[3]=now.day();
      menuValue[4]=now.hour();
      menuValue[5]=now.minute();
      menuValue[6]=now.second();
      
      delay(1000);
      lcd.clear();
      
    }
    
    bool processMenu(void) {
      static int lastPos=0;
      static int lastMenuLevel=-1;
    
      // Pre-empt menu level display 
      if (menuLevel!=lastMenuLevel) {
        lastMenuLevel=menuLevel;
     lcd.clear();
    ...
    Read more »

  • Updated Rotary Encoder Menu

    agp.cooper01/30/2018 at 08:24 1 comment

    Updated Rotary Encoder Menu

    I updated the Rotary Encoder menu for the LCD display:

    // Include LCD library and initialise
    #include <LiquidCrystal.h>
    // Define Adruino pin numbers for LCD
    #define en   7
    #define rs   8
    #define d4   9
    #define d5  10
    #define d6  11
    #define d7  12
    #define led 13
    // Set LCD
    LiquidCrystal lcd(rs,en,d4,d5,d6,d7);
    
    /* ROTARY ENCODER AND PUSH BUTTON POLLING CODE */
    #define Clk 2
    #define DT  3
    #define SW  4
    // Poll and debounces a Keyes rotary and push button switch
    // Inputs:
    //   Clk (Pin A with 10k pullup resistor)
    //   DT  (Pin B with 10k pullup resistor)
    //   SW  (Switch without a pullup resistor)
    //   +   (Power for pullup resistors)
    //   Gnd
    // Exports:
    //   UpdateSwitch (bool)   [true|false]
    //   Switch (byte)         [LOW|HIGH]
    //   EncoderPos (char)     [-128..127]
    volatile bool UpdateSwitch=false;
    volatile byte Switch=HIGH;
    volatile char EncoderPos=0;
    ISR(TIMER0_COMPB_vect) {
      static byte testClk=(PIND>>Clk)&1;
      static byte testDT=(PIND>>DT)&1;
      static byte lastClk=LOW;
      static byte lastDT=LOW;
      static bool flagClk=false;
      static bool flagDT=false;
      static char encoderDir=0;
      static byte testSW=HIGH;
      static byte statusSW=HIGH;
      static byte cntSW=0;  
      
      // Update Encoder Position
      lastClk=testClk;            // Save Clk
      lastDT=testDT;              // Save DT
      testClk=(PIND>>Clk)&1;      // Get Clk
      testDT=(PIND>>DT)&1;        // Get DT
      if (testClk!=lastClk) {     // Change in Clk?
        flagClk=true;             // Flag Clk has changed
        encoderDir=-1;            // Assume it is the last flag to change
      }
      if (testDT!=lastDT) {       // Change in DT?
        flagDT=true;              // Flag DT has changed
        encoderDir=1;             // Assume it is the last flag to change
      }
      if (flagClk&&flagDT) {      // Both flags have changed
        EncoderPos+=encoderDir;   // Update the encoder
        flagClk=false;            // Reset Clk flag
        flagDT=false;             // Reset DT flag
      }
      
      // Update switch with 10ms debounce
      testSW=(PIND>>SW)&1;
      if (testSW!=statusSW) {
        statusSW=testSW;
        cntSW=10;
      }
      if (cntSW>0) {
        cntSW--;
        if (cntSW==0) {
          Switch=statusSW;
          UpdateSwitch=true;
        }
      }
    }
    
    
    /* MENU SET UP */
    char* menuName[]={"Done ","Year ","Month ","Day ","Hour ","Minute ","Second ","Adjustment "};
    int menuSize=sizeof(menuName)/sizeof(char*);
    char menuValue[]=   {  0,  0,  1,  1,  0,  0,  0,   0};
    char menuNumeric[]= {'N','Y','Y','Y','Y','Y','Y', 'Y'};
    char menuValueMin[]={  0,  0,  1,  1,  0,  0,  0,-126};
    char menuValueMax[]={  1,126, 12, 31, 23, 59, 59, 126};
    char menuLevel=0;
    
    void setup() {
      // Initialise rotary encoder and push button
      pinMode(Clk,INPUT_PULLUP); // Rotary Clk
      pinMode(DT,INPUT_PULLUP);  // Rotary DT
      pinMode(SW,INPUT_PULLUP);  // Rotary SW
    
      // Turn on polling ISR
      OCR0B=0xA0;
      TIMSK0|=1<<OCIE0B;
    
      // Initialise LCD
      pinMode(led,OUTPUT);
      digitalWrite(led,HIGH);
      lcd.begin(16,2);
      lcd.print("Rotary Encoder");      
      delay(3000);   
    }
    
    bool processMenu(void) {
      static char lastPos=0;
      static char lastMenuLevel=-1;
    
      // Pre-empt menu level display 
      if (menuLevel!=lastMenuLevel) {
        lastMenuLevel=menuLevel;
        lcd.clear();
        lcd.setCursor(0,0);
        if (menuLevel==0) {
          lcd.print("Menu:");
          lcd.setCursor(0,1);
          lcd.print(menuName[EncoderPos]);
          if (menuNumeric[EncoderPos]=='Y') {
            lcd.print((int)menuValue[EncoderPos]);
          } else {       
            if (menuValue[EncoderPos]!=0) {
              lcd.print("Y");
            } else {
              lcd.print("N");      
            }
          }          
        } else if (menuLevel==1) {
          lcd.print("Set:");
          lcd.setCursor(0,1);
          lcd.print(menuName[lastPos]);
          if (menuNumeric[lastPos]=='Y') {
            lcd.print((int)menuValue[lastPos]);
          } else {       
            if (menuValue[lastPos]!=0) {
              lcd.print("Y");
            } else {
              lcd.print("N");      
            }
          }      
        } else {
          lcd.print("Rotary Encoder?");      
        }
      }
      
      // If push button pushed toggle menuLevel
      if (UpdateSwitch) {
        UpdateSwitch=false;
        if (Switch==LOW) {
          // Re-enter menu if button pushed (for long enough)
          if (menuLevel==-1) {
            menuLevel=0;    // Item menu
            lastPos=1;      // Trigger menu update 
            EncoderPos=0;   // Done
            menuValue[0]=0; // N
          } else {
            // Toggle menu level
            menuLevel=1-menuLevel;
            if (menuLevel==0) {
              // Save item menu position
              EncoderPos=lastPos;
              // Exit menu if done!
              if ((EncoderPos==0)&&(menuValue[EncoderPos]!=...
    Read more »

  • The Universal Time Clock

    agp.cooper01/30/2018 at 07:16 0 comments

    Universal Time

    Universal Time (UT) is the time in Greenwich UK. It is used for astromonical observations.

    This is a simple real time clock (rtc) project that uses and LCD to display the date and time in UT.

    Setting the time is automatic, it uses the compile time set local time and then reset that time to UT based on an upload adjustment and local time adjustments. 

    In my case the upload tme is 7 seconds, and my local time adjustment is -8 hours and 0 minutes. I live in Perth Western Australia and the longitude is 115.9 degrees East or 115.9 degrees. The local adjustment to the nearest hour is =-int(long/15+0.5), or -8 hours. Unfortunately many places have 30 minute local adjstments as well.

    Here is the code:

    // Include RTC libraries and initialise
    #include <Wire.h>
    #include "RTClib.h"
    RTC_DS1307 rtc;
    
    // Include LCD library and initialise
    #include <LiquidCrystal.h>
    // Define Adruino pin numbers for LCD
    #define en   7
    #define rs   8
    #define d4   9
    #define d5  10
    #define d6  11
    #define d7  12
    #define led 13
    // Set LCD
    LiquidCrystal lcd(rs,en,d4,d5,d6,d7);
    
    void setup() {
      // Turn on LCD LED
      pinMode(led,OUTPUT);
      digitalWrite(led,HIGH);
      
      // Setup LCD columns and rows
      lcd.begin(16, 2);
      
      // Print a message to the LCD.
      lcd.setCursor(0,0);lcd.print("Universal Time");
      // Check RTC
      if (!rtc.begin()) {
        lcd.setCursor(0,1);lcd.print("RTC not found");
        while (true);
      } else if (!rtc.isrunning()) {
        lcd.setCursor(0,1);lcd.print("RTC not running");
      } else {
        lcd.setCursor(0,1);lcd.print("RTC found");
      }
      
      // Set Universal Time based on Compile Time
      int localTimeHour=-8; // Perth Western Australia
      int localTimeMin=0;   // Perth Western Australia
      int uploadTimeSec=7;  // For my computer
    
      rtc.adjust(DateTime(F(__DATE__),F(__TIME__)));
      DateTime now=rtc.now();
      rtc.adjust(DateTime(now+TimeSpan(0,localTimeHour,localTimeMin,uploadTimeSec)));
      
      delay(1000);
      lcd.clear();
    }
    
    void loop() {
      
      DateTime now=rtc.now();
    
      // Print date on first line of LCD
      lcd.setCursor(0,0);
        lcd.print(now.year());
        lcd.print('/');
        if (now.month()<10) lcd.print(0);
        lcd.print(now.month());
        lcd.print('/');
        if (now.day()<10) lcd.print(0);
        lcd.print(now.day());
        
      // Print time on second line of LCD
      lcd.setCursor(0,1);lcd.print("UT: ");
        if (now.hour()<10) lcd.print(0);
        lcd.print(now.hour());
        lcd.print(':');
        if (now.minute()<10) lcd.print(0);
        lcd.print(now.minute());
        lcd.print(':');
        if (now.second()<10) lcd.print(0);
        lcd.print(now.second());
        
      delay(1000);
    }
    

    The only tricky bit here was setting UT after setting local time:

      // Set Universal Time based on Compile Time
      int localTimeHour=-8; // Perth Western Australia
      int localTimeMin=0;   // Perth Western Australia
      int uploadTimeSec=7;  // For my computer
    
      rtc.adjust(DateTime(F(__DATE__),F(__TIME__)));
      DateTime now=rtc.now();
      rtc.adjust(DateTime(now+TimeSpan(0,localTimeHour,localTimeMin,uploadTimeSec)));
    

    This line sets the rtc to compile time:

    rtc.adjust(DateTime(F(__DATE__),F(__TIME__)));

    This line get the current time (now):

    DateTime now=rtc.now();

    This line set UT based on an upload adjustment and local time adjustments:

    rtc.adjust(
      DateTime(
        now+TimeSpan(
          0,localTimeHour,localTimeMin,uploadTimeSec
        )
      )
    );


    Magic

     

  • Prototype (stripboard) done

    agp.cooper01/29/2018 at 14:59 0 comments

    Second stripboad prototype done

    I spent a lot of time getting this done.

    Here is the first prototype that got the LCD display working:

    And the final prototype design:

    Here is the assembled strip-board without the modules installed:

    And with the LCD and RTC running (it is checking my custom clock):

    Next step

    Next is to get the menu system integrated.

    Front panel

    Now that the components have been located I can design the front panel.

    Finally

    The idea is that once I have a fully worked out prototype (complete with housing and power supply), I will get some PCBs made so I can reuse the design for other projects.

    Magic

  • Adding an LCD Display

    agp.cooper01/26/2018 at 22:38 0 comments

    Adding an LCD Display

    What is so hard? Just use the LCD library. Actually the problem is hooking it up in a semi-permanent way rather than the using the LCD library.

    Issues

    • Which pins to use
    • Controlling the LED
    • Controlling the contrast

    When I first layout the strip-board for the display adapter I first used the standard pin numbers as shown below:

    Except I used D6 and D7 for "E" and "RS", and D8 to control the LED power.

    The first problem was adding a rotary encoder. The first rotary encoder code used two rising level interrupts and on the Uno/Nano you have to use D2 and D3. So I shuffled all the LCD pin number down by three (D4 was to be used for the switch). Leaving D12, D13 (the LED) and the analog pins free.

    As the design progressed I realised it would be nice to keep the interrupt and PWM pins free, and I decided to use polling as I had to deal with switch bounce anyway.

    For contrast a 1k8 resistor to ground work okay but access for contrast adjustment was provided.

    Here is my strip-board design:

    Magic

  • Adding a Simple Menu System

    agp.cooper01/26/2018 at 13:55 0 comments

    A Simple Menu System

    As a demo I added a clock set menu. Here is a drawing of the menu and the value ranges:

    So it is pretty simple, two levels: "Menu Item" and "Item Value". Just roll the encoder to move from one item to the next, push the button to toggle between levels. To exit the menu just toggle the done value from "N" to "Y" and push the button again. To get back into the menu, push the button (at least as long as any delays in the main loop).

    The "Item Value" do have minimum and maximum vaues enforced but it does not know that February cannot have 31 days!  Enter 18 for the year 2018, etc.

    Here are my menu arrays:

    char* menuName[]={"Done   ","Year   ","Month  ","Day    ","Hour   ","Minute ","Second "};
    int menuSize=sizeof(menuName)/sizeof(char*);
    char menuValue[]=   {  0,  0,  1,  1,  0,  0,  0};
    char menuNumeric[]= {'N','Y','Y','Y','Y','Y','Y'};
    char menuValueMin[]={  0,  0,  1,  1,  0,  0,  0};
    char menuValueMax[]={  1,126, 12, 31, 23, 59, 59};
    char menuLevel=0;

    The menu item names include the necessary format spacing between the name and the value. And values can be numeric ('Y') or Y/N ('N').

    Here is the code:

    #define Clk 5
    #define DT  4
    #define SW  3
    // Poll and debounces a Keyes rotary and push button switch
    // Inputs:
    //   Clk (Pin A with 10k pullup resistor)
    //   DT  (Pin B with 10k pullup resistor)
    //   SW  (Switch without a pullup resistor)
    //   +   (Power for pullup resistors)
    //   Gnd
    // Exports:
    //   UpdateSwitch (bool)   [true|false]
    //   Switch (byte)         [LOW|HIGH]
    //   EncoderPos (char)     [-128..127]
    volatile bool UpdateSwitch=false;
    volatile byte Switch=HIGH;
    volatile char EncoderPos=0;
    ISR(TIMER0_COMPA_vect) {
      static byte testClk=(PIND>>Clk)&1;
      static byte testDT=(PIND>>DT)&1;
      static byte lastClk=LOW;
      static byte lastDT=LOW;
      static bool flagClk=false;
      static bool flagDT=false;
      static char encoderDir=0;
      static byte testSW=HIGH;
      static byte statusSW=HIGH;
      static byte cntSW=0;  
      
      // Update Encoder Position
      lastClk=testClk;            // Save Clk
      lastDT=testDT;              // Save DT
      testClk=(PIND>>Clk)&1;      // Get Clk
      testDT=(PIND>>DT)&1;        // Get DT
      if (testClk!=lastClk) {     // Change in Clk?
        flagClk=true;             // Flag Clk has changed
        encoderDir=-1;            // Assume it is the last flag to change
      }
      if (testDT!=lastDT) {       // Change in DT?
        flagDT=true;              // Flag DT has changed
        encoderDir=1;             // Assume it is the last flag to change
      }
      if (flagClk&&flagDT) {      // Both flags have changed
        EncoderPos+=encoderDir;   // Update the encoder
        flagClk=false;            // Reset Clk flag
        flagDT=false;             // Reset DT flag
      }
      
      // Update switch with 10ms debounce
      testSW=(PIND>>SW)&1;
      if (testSW!=statusSW) {
        statusSW=testSW;
        cntSW=10;
      }
      if (cntSW>0) {
        cntSW--;
        if (cntSW==0) {
          Switch=statusSW;
          UpdateSwitch=true;
        }
      }
    }
    
    char* menuName[]={"Done   ","Year   ","Month  ","Day    ","Hour   ","Minute ","Second "};
    int menuSize=sizeof(menuName)/sizeof(char*);
    char menuValue[]=   {  0,  0,  1,  1,  0,  0,  0};
    char menuNumeric[]= {'N','Y','Y','Y','Y','Y','Y'};
    char menuValueMin[]={  0,  0,  1,  1,  0,  0,  0};
    char menuValueMax[]={  1,126, 12, 31, 23, 59, 59};
    char menuLevel=0;
    
    void setup() {
    
      // Keyes rotary encoder
      pinMode(Clk,INPUT_PULLUP); // Rotary Clk (has 10k pullup)
      pinMode(DT,INPUT_PULLUP);  // Rotary DT  (has 10k pullup)
      pinMode(SW,INPUT_PULLUP);  // Rotary SW  (has no pullup)
      pinMode(2,OUTPUT);         // Rotary + (supply power to encoder)
      digitalWrite(2,HIGH);      // Turn on power for rotary encoder
    
      // Turn on polling ISR
      OCR0A=0x80;
      TIMSK0|=1<<OCIE0A;
    
      Serial.begin(9600);
      while (!Serial);
    
      Serial.println("Rotary encoder and push button example");
      Serial.println("ITEM   VALUE");
      Serial.print(menuName[EncoderPos]);
      if (menuNumeric[EncoderPos]=='Y') {
        Serial.println(menuValue[EncoderPos],DEC);
      } else {       
        if (menuValue[EncoderPos]!=0) {
          Serial.println("Y");
        } else {
          Serial.println("N");      
        }
      }
    }
    
    bool processMenu(void) {
      static char lastPos=0;
        
      // If push button pushed toggle menuLevel
      if (UpdateSwitch) {
        UpdateSwitch=false;
        if (Switch==LOW) {
          // Re-enter menu if button pushed (for long enough)
          if (menuLevel==-...
    Read more »

View all 10 project logs

Enjoy this project?

Share

Discussions

agp.cooper wrote 02/04/2018 at 00:38 point

Hi David,

I have finished with this project. I have put a cut down version of the code, "RotaryEncoderBlink", in the files directory. It has a simple menu system that uses the serial port to set the blink rate.

It works fine providing you don't turn the encoder too fast (i.e. spin it!).

AlanX

  Are you sure? yes | no

agp.cooper wrote 02/03/2018 at 13:35 point

I just completed the code to my satisfaction and it is working well.
In my files area is "DaylightSampler.ino", it is my current version.
Its a rather big file doing lots of things, so strip out what you don't need.
Hopefully your rotary encoder is not a double signal version like mine!

AlanX

  Are you sure? yes | no

David H Haffner Sr wrote 02/03/2018 at 12:28 point

Thanks for posting this, it has just solved a really big problem I was encountering with my targeting system!

  Are you sure? yes | no

Similar Projects

Does this project spark your interest?

Become a member to follow this project and never miss any updates