Example Code for Raspberry Pi - Set LCD Color (C++)

Last revision 2026/01/20

This article offers a comprehensive guide to setting RGB LCD colors using C++ on Raspberry Pi. It includes hardware and software preparation, wiring instructions, and sample code to help users effectively execute and customize the color settings on their Raspberry Pi LCD screens.

Hardware Preparation

Software Preparation

Wiring Diagram

Install the RGB LCD KeyPad HAT directly onto the Raspberry Pi board.

Other Preparation Work

  1. Enable I2C on Raspberry Pi:
    Input sudo raspi-config in the terminal, then select Interfacing Options (or Advanced Options) → I2CYesOKFinish.
    Interfacing Options
    I2C
    Yes
    OK
    Finish

  2. Detect the I2C address of the HAT:
    Run sudo i2cdetect -y 1 to confirm the device is recognized.
    sudo i2cdetect -y 1

  3. Download the library:

    • Via GitHub: git clone https://github.com/DFRobot/DFRobot_RGB1602_RaspberryPi.git
    • Via USB: Download the library to a USB drive and copy it to the Raspberry Pi.
  4. Install I2C test tool: sudo apt-get install i2c-tools

  5. Install Vim (optional, for code editing): sudo apt-get install vim-gtk

Sample Code


    #include "../DFRobot_RGBLCD.h"
    #include <iostream>
    #include <string>

    using namespace std;

    int main(){
      int r,g,b;

      DFRobot_RGBLCD lcd(16, 2);
      // initialize
      lcd.init();
      // Print a message to the LCD.
      lcd.print("set cllor");

      while(1){
        cout << "r:";
        cin >> r;
        cout << "g:";
        cin >> g;
        cout << "b:";
        cin >> b;

        lcd.setRGB(r, g, b);

        cout << "r = " << r
             << "g = " << g
             << "b = " << b
             << endl;
      }
      return 0;
    }

}

Result

Function: set the color of the RGB LCD screen

Result: input r: 255 g: 0 b: 0 then the screen displays red.

  • To check or edit codes, you can download them to Windows and then open directly, or input the command vim SetColor.cpp under the catelogue DFRobot_RGB1602_RaspberryPi/cpp/examples in Raspberry Pi system.

Note: vim compiler needs to be installed first then you can continue the above operations. vim install command: sudo apt-get install vim-gtk

  • Save and exit: press ESC key, then press shift+zz(or switch to uppercase mode and press ZZ);

  • Exit without saving: press ESC key, then type a colon, and input the command "q!".

Additional Information

  • To edit the code: Run vim SetColor.cpp in the DFRobot_RGB1602_RaspberryPi/cpp/examples directory.
  • Save and exit Vim: Press ESCShift+ZZ.
  • Exit without saving: Press ESC → type :q! → press Enter.

Open c program in Vim

Was this article helpful?

TOP