Friday, January 30, 2015

A spinning top for your LCD





Sometimes we need to wait for the end of a task or for an event to occur and at the same time to keep the user informed that the system is not hung. This is the right occasion for a spinning top!

In this post we propose a very simple one. Indeed, it is a good occasion to see how to use the character generator of the LCD and insert new character. The module that we are going to use is based on the famous Hitachi HD44780 chip. This chip has the possibility to increase its char set with 4 additional user defined chars. This easily done using the command createChar which take in input the id code for the new char (an integer between 0 and 3) and an array of 8 bytes which are interpreted as a bitmap (here we use the 5x8 charset).

What you need
  • 1x Arduino Uno
  • 1x LCD module
Just that! For more on the LCD module you can also have a look here.

Configuration
Modify the definitions of the pins to adapt to your LCD module. In order to change the speed of the spinner decrease the value of FRAMETIME. This variable control the frame rate. Indeed, frame rate is approx 1/FRAMETIME.

The sketch
/**
 * Spinning top
 *
 * \author Enrico Formenti
 * \version 1.0
 * \date 30 january 2015
 *  \copyright BSD license, check the License page on the blog for more information. All this text must be 
 *  included in any redistribution.
 *  <br><br>
 *  See macduino.blogspot.com for more details.
 */

#include <LiquidCrystal.h>

// modify the definitions below according to your LCD module
 
#define LCD_RS_PIN 7
#define LCD_ENABLE_PIN 6
#define LCD_DATA4_PIN 5
#define LCD_DATA5_PIN 4
#define LCD_DATA6_PIN 3
#define LCD_DATA7_PIN 2

LiquidCrystal lcd(LCD_RS_PIN, LCD_ENABLE_PIN, LCD_DATA4_PIN,
                  LCD_DATA5_PIN, LCD_DATA6_PIN, LCD_DATA7_PIN);


// modify the value below to change the frame rate
// framerate per second is approx 1/FRAMETIME 
#define FRAMETIME 120


// the backslash character is not in the standard char set
// of the LCD so let's redefine it

uint8_t backslash[8] = {
    0b00000,
    0b10000,
    0b01000,
    0b00100,
    0b00010,
    0b00001,
    0b00000,
    0b00000
};

// we use special character 0 here
char spinningTop[] = {'/', '-', 0, '|'};
uint8_t k;

void setup() {
  // put your setup code here, to run once:
  k = 0; // init spinner
  
  // init screen
  lcd.begin(16, 2);
  lcd.createChar(0, backslash);
  lcd.clear();
  lcd.print("Look at me... ");
}

void loop() {
  // update spinner and...
  lcd.setCursor(14,0);
  lcd.write(spinningTop[k%4]);
  k = (k+1) & 0b11;
  // ...waste some time to let user see it spinning
  delay(FRAMETIME);
}

Suggestions
Remark that our implementation of the spinner uses busy waiting. In order to avoid it one can use interrupts. However, if you decide to use interrupts, recall that they can interfere with other modules or sensors and that Arduino Uno only has two of them!

Enjoy!

No comments :

Post a Comment