Color Sensing in Embedded Applications

 Objective

Sorting items by color has many real-world applications. For example, in the food industry, a vegetable sorter requires a color sensor to detect the color of different vegetables to be able to sort them. They are also used in industrial sorting for segregating colored recycled plastic, coffee beans, and car interiors. The goal of this project is to demonstrate how you can use a PIC® microcontroller to sense color from a light source or an opaque object and display the detected color on an OLED display. Many industrial applications for color sensing depend on multiple factors (i.e., the number of colors detected, the accuracy of color detected, response time, proximity and brightness of the color source).

 Color Sensing Demo

 Materials

Hardware Tools

Tool About Purchase
ICD3-50px.png
MPLAB® ICD 3
In-Circuit Debugger

Software Tools

Tool About Installers
Installation
Instructions
Windows Linux Mac OSX
MPLAB® X
Integrated Development Environment
swtool-28px.png
MPLAB® Code Configurator
Dynamic Code Generation
MPLAB® XC8
C Compiler

Exercise Files

File Download
Installation
Instructions
Windows Linux Mac OSX
Project and Source Files

 Connection Diagram

BlockDiagram.png

Make sure the following jumpers are present on the Explorer 8 Development Board to ensure the project works properly:

  1. No need for any jumpers on components 1-6.
  2. In component 7, configure the jumpers such that:
    • J47: RD6 is connected with the center pin to configure it as the microcontroller SCK pin that connects to the J32 mikroBUS SCK (SPI Clock).
    • J46: RD5 is connected with the center pin to configure it as the microcontroller SDI pin that connects to the J32 mikroBUS MISO (SPI Master Input Slave Output) pin.
    • J45: RD4 is connected with the center pin to configure it as the microcontroller SDO pin that connects to the J32 mikroBUS MOSI (SPI Master Output Slave Input) pin.
  3. No need for any jumpers on components 8-14.
  4. In component 15, configure the jumpers such that:
    • J30, J14: The board is supplied with 3.3 V.
  5. In component 16, configure the jumpers such that:
    • J2: The board is supplied with 5 V power via the output of the 5 V regulator.
  6. In component 17, configure the jumpers such that:
    • J51, J52: RB7 is connected with the center pin at J51 and RB6 is connected with the center pin at J52 to connect the PGD and PGC pins of the ICD to the PIC® MCU ICSPDAT and ICSPCLK, respectively for ICSP™
  7. No need for any jumpers on component 18.
  8. In component 19, configure the jumpers such that:
    • J24: The two pins are connected to each other to supply a regulated 3.3 V output to the mikroBUS.
Jumpers.png

 Procedure

The major steps to implement this project are as follows:

  • Set up Project Resources
  • Set up the MSSP modules
  • Configure the Pin Manager
  • Generate code
  • Add functionality
  • Program the device

1

Create New Project

Create a new "Standalone" project in MPLAB® X for a PIC16F18875. If this is your first time using MPLAB® X, follow the instructions in the following article: Create a Standalone Project.

2

Launch MPLAB Code Configurator

Open the MPLAB® Code Configurator under the Tools > Embedded menu of MPLAB® X IDE as shown in the image below.

OpenMCC.png

3

Set up Project Resources

The System Module needs to be set up. Click on 'System Module' in the "Project Resources" section.

ProjectResources.png

The 'System' section will appear. In this section, the oscillator settings and the configuration settings are selected.

Oscillator

  1. Select the 'HFINTOSC (1MHz)' from the drop-down menu for the Oscillator Select option.
  2. Select the '4_MHz' option from the HF Internal Clock drop-down menu.
  3. Select '4' from the Clock Divider drop-down menu.
  4. Check the 'Low-voltage programming Enable' selection.

This will enable the internal 4 MHz high-frequency internal oscillator as the system clock.

SystemModule.png

Configuration

Each configuration setting can be changed under the 'Register' tab of the System window.

Verify that the MPLAB Code Configurator generated settings are set to the default values shown here.

CONF1.png
CONF2.png
CONF3.png
CONF4.png
CONF5.png

4

Set up the MSSP1 Module

The MSSP1 needs to be set up. Click on the 'MSSP1' label in the "Project Resources" section to make the MSSP1 setup screen appear.

MSSP1.png

MSSP1 is used for I2C communication between the master PIC controller and the slave Color Click. Select the 'I2C Master' Mode and verify the other values are set to the default values shown here.

MSSPSettings.png

5

Setup the MSSP2 Module

The next step is to setup the MSSP2 module. Click on the 'MSSP2' in the "Project Resources" section shown below.

MSSP2.png

MSSP2 is used for SPI Communication between the master PIC controller and the slave OLED B Click. Select the 'SPI Master' Mode and verify the other values are set to the default values shown here.

MSSP2Settings.png

6

Configure Pin Manager

There are multiple pins that need to be set in the Pin Manager window.

PinManager.png
PinManager2.png

At the end of this step, the Pin Manager window should look like this:

FinalPinConfig.png

7

Custom Names for Pins

Close the Pin Manager window and then click on 'Pin Module' in the "Project Resources" section.

ProjectResourcesPins.png

Rename the pins according to the following diagram. To rename a pin, click on the 'Custom Name' for the pin and type in the new name. Make sure all the 'Analog' and 'WPU' boxes are not checked. If any are checked, click on the box to uncheck them.

PinNames.png
RenamedPins.png

8

Generate Code

Click on the Generate Code button to have the MCC create the software libraries for this project.

Generate.png

The project will now have both generated Header Files and Source Files. It should also have a generated main.c file.

Projects.png

9

Adding Functionality

Functionality.png

There are four files that need to be attached to the project to make use of their functionalities. Download the project ZIP file from the "Exercise Files" section of this page and expand the contents. Then move or copy the files oled.c, oled.h, color.c and color.h to the working project folder. The following steps will teach you how to do that.

Files.png

a

Go back to MPLAB® X IDE v4.01. Right click on 'Source Files' in the 'Project' tab.

b

Right click on 'Add Existing Item' from the drop down menu.

AddExistingItem.png

c

Choose oled.c and color.c and click on Select.

SelectFiles.png

The 'Projects' tab must look like the following picture after adding the files:

FilesAdded.png

d

Now right click on 'Header Files' in the 'Project' tab.

e

Right click on 'Add Existing Item' from the drop down menu.

AddExistingItem2.png

f

Choose oled.h and color.h and click on Select.

HeaderFilesAdded.png

The 'Projects' tab must look like the following picture after adding the files:

HeaderFiles.png

This will add the files and you can use the functionality that it provides.

Note: The file attached to the project has all the snippets together and needs no modification if used directly. You may also use the snippets on this article to write the code from a new file.

10

oled.c

Once the file is attached to the project, the OLED display functions can be called to utilize its functionality.

  • OLED_Command() function can be used to call OLED SSD1306 display driver commands for reset, contrast control, and other basic commands understood by the OLED.

Display driver controller functions are called using the following code snippet:

  • OLED_Data() function is used to define a character that has to be displayed on the OLED B click board.

The following snippet issues the pixel pattern for a character to be displayed where temp is the character to be displayed:

  • OLED_Initialize() function initializes the OLED to function properly.

A set of commands are sent over SPI data line to initialize the OLED B click board.

  • OLED_SetRow() and OLED_SetColumn() functions set which row and column the character has to be displayed on.

The following snippet sets the row at which a character has to be displayed:

The following snippet sets the column at which a character has to be displayed:

  • OLED_PutPicture() function is used to define what the complete OLED has to print out or display and to talk to the OLED B Click display through SPI.

The following code snippet displays the complete image of the OLED B click board:

  • OLED_Clear() function displays a plain screen.

To each row and column, writing a 0x00 will make the screen blank and can be implemented as follows:

11

oled.h

This header file has function prototypes of the functions that need to be used in the oled.c file. It also defines the basic display driver commands that need to be sent to the OLED for initialization and defines what character corresponds to which pattern.

12

color.c

Once the file is attached to the project, the color click functions can be called to utilize its functionality.

  • Color_Initialize() function initializes the color click to perform its basic functions.

First, enable register as follows:

Next, add a delay as in the folowing code snippet:

This step is optional. Provide a light source for opaque objects if needed as follows:

  • Color_Read() reads the red, green, blue and clear content of the registers that hold the data for the color sensor click using I2C read and write.

First, read the clear light intensity using the following lines of code:

Next, read the respective red, green and blue color values from their data registers:

To normalize the data, each color is divided by the ClearData value as follows:

Finally, the Hue value is computed using the formula shown below:

  • Read_Register_Data() function reads data from the register located in a specified register in the color sensor and returns the read value.

To be able to read a data register on the color sensor click board, the address of the data register is written on the I2C bus as follows:

The write has to be followed by the read to obtain the value of red, green, blue and clear data registers with delay after each I2C read/write operation to ensure proper data on the bus. This is done using the following snippet:

Lastly, return the data that is read as follows:

  • Modify_Data() function modifies characters that need to be printed out on the OLED B display click.

Two for loops are used to write a character array onto the OLED B click board as follows:

  • Modify_Spaces() function adds blank spaces on the OLED display.

To write spaces onto the OLED B click board, a value of 0x00 is written.

  • Color_Display() function displays what color is sensed by the color sensor click.

Based on the hue value, a color is predicted using an if-else ladder as follows:

Data to be written is modified with the right spacing and the image is displayed on the OLED B Click board using the following snippet:

Further, the other colors are predicted using the hue value range.

13

color.h

This header file has function prototypes of the functions that need to be used in the color.c file. It also declares member variables that are used in the color.c file.

14

main.c

The main file needs modifications to incorporate color sensing. To add them, double click on the main.c file to open it up in the editor window.

main.png

a

The main.c file requires a few lines to be uncommented for Global and Peripheral Interrupts to work properly. MCC already has the control commands in the default main.c file, but they are commented out with two forward slashes (//). The forward slashes need to be removed to enable these lines of code.

EnableInterrupts.png

b

To include the functionality defined for the click boards, the header files oled.h and color.h have to be included in the main file. The following lines are included before the main() function definition:

IncludeFiles.png

c

The OLED B Click and the Color Click have to be initialized. For OLED B Click to be initialized, call the OLED_Initialize function.

InitOLED.png

For the Color Click to be initialized, call the Color_Initialize function.

ColorInit.png

d

To sense the color, the function Color_Read() has to be called and to display the color on the OLED B Click, the function Color_Display() has to be called. This sensing and displaying will be done continuously in a forever while loop as follows:

ColorFunctions.png

15

Programming the Device

Make sure your project has the programming tool selected and that your development board is connected to power. Click on the Make and Program Device icon. This will build the project and launch the programmer. In the output window, you should see a series of messages and if successful it will end with a Programming and Verify Successful message.

VerifyComplete.png

The color displayed in front of the color sensor will be identified and the OLED B Click will display the color on its screen with R, G and B values in hexadecimal values. This will run continuously.

16

Closing the Project

The project can be closed in MPLAB® X IDE v4.01. The project is saved automatically when it is built, but if any changes to files or configuration were made, MPLAB X will ask you to save them before the project is closed. The project can be closed under the File > Close Project.

CloseProject.png

 Results

You have now seen how you can use a PIC microcontroller to sense color from a light source or an opaque object and display the detected color on an OLED display.

© 2024 Microchip Technology, Inc.
Notice: ARM and Cortex are the registered trademarks of ARM Limited in the EU and other countries.
Information contained on this site regarding device applications and the like is provided only for your convenience and may be superseded by updates. It is your responsibility to ensure that your application meets with your specifications. MICROCHIP MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED, WRITTEN OR ORAL, STATUTORY OR OTHERWISE, RELATED TO THE INFORMATION, INCLUDING BUT NOT LIMITED TO ITS CONDITION, QUALITY, PERFORMANCE, MERCHANTABILITY OR FITNESS FOR PURPOSE. Microchip disclaims all liability arising from this information and its use. Use of Microchip devices in life support and/or safety applications is entirely at the buyer's risk, and the buyer agrees to defend, indemnify and hold harmless Microchip from any and all damages, claims, suits, or expenses resulting from such use. No licenses are conveyed, implicitly or otherwise, under any Microchip intellectual property rights.