While working on projects using the RGB LCD shield, I’m finding it handy to see different character / color combinations on the screen. I’ve written a sketch that allows me to page through all the available characters using the left and right buttons and all available backlight colors using the up and down buttons (this also works with the negative version of the RGB LCD shield).
All the characters on the bottom row share the same four high bits; the character representing those four bits is indicated in the top row by underlining (in the above picture, the number seven is underlined indicating that all characters in the bottom row have a character code starting with seven). The characters are displayed below the digit representing the low four bits for the character code. In the above picture, the left arrow is under the F character, so the code for left arrow is 0x7F. Following the same logic, the code for q is 0x71.
There are a few areas in the code worth calling out. The first is the function that treats a button press and release as a single click. The shield library provides readButtons(), which is a handy function for reading the current state of the buttons. You can detect clicks by calling readButtons() at regular intervals and performing some bitwise operations on the results. The first step is performing a bitwise XOR (exclusive OR) on two consecutive reads to get a bitmask value showing which buttons changed state:
This value needs to be further filtered to find out which buttons were released on the second read. Performing a bitwise negation on the second value produces a new value where the off buttons are ones and the on buttons are zeros. This value can be bitwise ANDed with the changed button value to get a new value where clicked buttons are ones and all other buttons are zeros.
Which can be represented in code as follows:
uint8_t read_clicked_buttons() { // Static variables are intialized once and hold value between calls to the function. static uint8_t last_buttons = 0; // Read which buttons are currently on. uint8_t current_buttons = lcd.readButtons(); // Calculate which buttons changed state since the last read. uint8_t changed_buttons = last_buttons ^ current_buttons; // Calculate which buttons are currently off. uint8_t off_buttons = ~current_buttons; // Calculate which buttons transitioned from on to off between reads. uint8_t clicked_buttons = changed_buttons & off_buttons; // Store current buttons for next call. last_buttons = current_buttons; return clicked_buttons; }
The second interesting section is the underlining of the selected column. This is implemented by manipulating the cursor settings as the last step when drawing the screen:
lcd.noCursor(); // draw screen lcd.setCursor(char_offset, 0); lcd.cursor();
Full source is available on github.