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
- Raspberry Pi 4B x 1
- RGB LCD KeyPad HAT x1
- HDMI Cable x1
- Display x1
- Keyboard and Mouse x1
Software Preparation
- Raspberry Pi OS
- Download DFRobot_RGB1602_RaspberryPi library (via GitHub or USB)
Wiring Diagram
Install the RGB LCD KeyPad HAT directly onto the Raspberry Pi board.
Other Preparation Work
-
Enable I2C on Raspberry Pi:
Inputsudo raspi-configin the terminal, then select Interfacing Options (or Advanced Options) → I2C → Yes → OK → Finish.





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

-
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.
- Via GitHub:
-
Install I2C test tool:
sudo apt-get install i2c-tools -
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.cppin theDFRobot_RGB1602_RaspberryPi/cpp/examplesdirectory. - Save and exit Vim: Press
ESC→Shift+ZZ. - Exit without saving: Press
ESC→ type:q!→ pressEnter.

Was this article helpful?
