# MeRGBLineFollower Arduino Library Documentation

**Library Author**: MakeBlock  
**Adapted by**: Community contributions  
**Last Updated**: 2025-05-01  

This document describes the public functions available in the `MeRGBLineFollower` Arduino library, designed to interact with the MakeBlock RGB Line Follower module using I2C.

> This documentation has been generated by ChatGPT and is intended for educational purposes. It may not cover all edge cases or specific implementations. Always refer to the code for the most accurate and up-to-date information.

---

# Table of Contents
- [MeRGBLineFollower Arduino Library Documentation](#mergblinefollower-arduino-library-documentation)
- [Table of Contents](#table-of-contents)
- [Constructor](#constructor)
- [Initialization](#initialization)
  - [`void begin();`](#void-begin)
  - [`void setpin(uint8_t AD0, uint8_t INT);`](#void-setpinuint8_t-ad0-uint8_t-int)
- [Sensor Readings](#sensor-readings)
  - [`void updataAllSensorValue();`](#void-updataallsensorvalue)
  - [`uint8_t getADCValueRGBX();`](#uint8_t-getadcvaluergbx)
  - [`void loop();`](#void-loop)
- [Line Tracking](#line-tracking)
  - [`int16_t getPositionOffset();`](#int16_t-getpositionoffset)
  - [`uint8_t getPositionState();`](#uint8_t-getpositionstate)
  - [`void setKp(float value);`](#void-setkpfloat-value)
- [Threshold Settings](#threshold-settings)
  - [`int8_t setBackgroundThreshold(uint8_t ch, uint8_t threshold);`](#int8_t-setbackgroundthresholduint8_t-ch-uint8_t-threshold)
  - [`int8_t setTrackThreshold(uint8_t ch, uint8_t threshold);`](#int8_t-settrackthresholduint8_t-ch-uint8_t-threshold)
  - [`uint8_t getBackgroundThreshold(uint8_t ch);`](#uint8_t-getbackgroundthresholduint8_t-ch)
  - [`uint8_t getTrackThreshold(uint8_t ch);`](#uint8_t-gettrackthresholduint8_t-ch)
- [RGB LED Control](#rgb-led-control)
  - [`int8_t setRGBColour(uint8_t colour);`](#int8_t-setrgbcolouruint8_t-colour)
- [Firmware](#firmware)
  - [`void getFirmwareVersion(char *buffer);`](#void-getfirmwareversionchar-buffer)
- [Learning Mode](#learning-mode)
  - [`uint8_t getStudyTypes();`](#uint8_t-getstudytypes)
  - [`int8_t studyBackground();`](#int8_t-studybackground)
    - [🔍 **Purpose of `studyBackground()`**](#-purpose-of-studybackground)
    - [⚙️ **How it works**](#️-how-it-works)
    - [✅ **When to use it**](#-when-to-use-it)
    - [💡 Example usage](#-example-usage)
  - [`int8_t studyTrack();`](#int8_t-studytrack)
    - [🔍 **Purpose of `studyTrack()`**](#-purpose-of-studytrack)
    - [⚙️ **How it works**](#️-how-it-works-1)
    - [✅ **When to use it**](#-when-to-use-it-1)
    - [📌 Example: Full Calibration Sequence](#-example-full-calibration-sequence)
    - [🔧 Notes](#-notes)
- [Calibration Guide: `studyBackground()` and `studyTrack()`](#calibration-guide-studybackground-and-studytrack)
  - [`studyBackground()`](#studybackground)
  - [`studyTrack()`](#studytrack)
  - [Full Example Sequence](#full-example-sequence)
  - [`getStudyTypes()`](#getstudytypes)
- [Summary Table of Public Functions](#summary-table-of-public-functions)
  - [Notes:](#notes)


---

# Constructor

```cpp
MeRGBLineFollower(uint8_t port = 0);
```

Creates an instance of the RGB Line Follower. The port parameter refers to the RJ25 port on Makeblock boards.

---

# Initialization

## `void begin();`

Initializes I2C communication and prepares the device for operation.

## `void setpin(uint8_t AD0, uint8_t INT);`

Sets the control pins for address selection when not using Makeblock ports.

---

# Sensor Readings

## `void updataAllSensorValue();`

Reads all sensor values and updates internal buffers.

## `uint8_t getADCValueRGBX();`

```cpp
uint8_t getADCValueRGB1();
uint8_t getADCValueRGB2();  
uint8_t getADCValueRGB3();  
uint8_t getADCValueRGB4();
```
Returns the raw analog value (0–255) of each of the 4 RGB sensors.

## `void loop();`

Efficiently manages sensor polling.  
This method should be called periodically in your Arduino `loop()`. It internally calls `updataAllSensorValue()` only if at least 8 milliseconds have passed, reducing I2C bus congestion and avoiding redundant updates.

💡 **Recommended usage**: Call `tracker.loop();` inside your `loop()` function instead of `updataAllSensorValue()` directly.

---

# Line Tracking

## `int16_t getPositionOffset();`

Returns the deviation from the center line. Range is -512 (far right) to +512 (far left). Uses PID logic internally.

## `uint8_t getPositionState();`

Returns a 4-bit binary value representing the state of each sensor:
- bit0: RGB1
- bit1: RGB2
- bit2: RGB3
- bit3: RGB4

Each bit is 1 if the corresponding sensor detects the track.

## `void setKp(float value);`

Sets the proportional constant (0.0 to 1.0) used in position offset calculation.

---

# Threshold Settings

## `int8_t setBackgroundThreshold(uint8_t ch, uint8_t threshold);`  
## `int8_t setTrackThreshold(uint8_t ch, uint8_t threshold);`

Sets the background or track detection threshold for sensor index `ch` (0 to 3).

## `uint8_t getBackgroundThreshold(uint8_t ch);`  
## `uint8_t getTrackThreshold(uint8_t ch);`

Returns the current threshold for background or track detection.

---

# RGB LED Control

## `int8_t setRGBColour(uint8_t colour);`

Sets the LED color on the sensor. Accepted values:
- `RGB_COLOUR_RED` (1)
- `RGB_COLOUR_GREEN` (2)
- `RGB_COLOUR_BLUE` (3)

---

# Firmware

## `void getFirmwareVersion(char *buffer);`

Fills the buffer with 8 bytes representing the firmware version string.

---

# Learning Mode

## `uint8_t getStudyTypes();`

Returns the study mode state:
- 0 = Idle
- 1 = Learning Background
- 2 = Learning Track

## `int8_t studyBackground();`  

The `studyBackground()` function on the `MeRGBLineFollower` sensor module triggers a **calibration process** where the sensor learns what the background surface looks like (i.e., the *non-line* surface). Here's how it works and why it's important:

---

### 🔍 **Purpose of `studyBackground()`**

It allows the module to **automatically detect the baseline (background) light reflection levels** from the surface **that is *not* the line**. This is important because:

- Different lighting conditions and surfaces reflect light differently.
- The sensor uses this "learned" value to better **distinguish the line from the background** during operation.

---

### ⚙️ **How it works**

- Internally, it sends a command via I2C to set the module into background calibration mode.
- Each of the 4 RGB sensors records the ambient reflectance value of the surface underneath.
- These values are saved in the module’s threshold registers (`RGBx_BACKGROUND_THRESHOLD`), and are used later in real-time line detection.

---

### ✅ **When to use it**

You should call `studyBackground()`:
1. After initializing the module (`begin()`),
2. When the robot is **placed on the background surface**, **not over the line**,
3. And ideally before calling `studyTrack()` (which detects the line itself).

---

### 💡 Example usage

```cpp
tracker.begin();
tracker.setRGBColour(RGB_COLOUR_GREEN);
delay(1000);

// Place the robot on the background (not on the line)
tracker.studyBackground();
delay(500);

// Now place it over the line for track learning
tracker.studyTrack();
```

---

## `int8_t studyTrack();`

### 🔍 **Purpose of `studyTrack()`**

The `studyTrack()` function tells the `MeRGBLineFollower` module to **learn what the line looks like** by recording the light reflectance values from the surface **where the line is present**. This value is used to distinguish the line from the background during operation.

---

### ⚙️ **How it works**

- When called, the module switches to **line calibration mode**.
- It samples the light intensity reflected by the surface *under the line* (usually darker than the background).
- These values are stored internally in the `TRACK_THRESHOLD` registers for each sensor.

---

### ✅ **When to use it**

You should call `studyTrack()`:
1. **After** calling `studyBackground()`,
2. When the **robot is positioned directly over the line** (with the sensors aligned),
3. Before starting normal line-following behavior.

This ensures the sensor knows both the "off-line" (background) and "on-line" (track) reflectance levels, which improves its detection accuracy.

---

### 📌 Example: Full Calibration Sequence

```cpp
tracker.begin();
tracker.setRGBColour(RGB_COLOUR_GREEN);
delay(1000);

// 1. Place on background (not on line)
tracker.studyBackground();
delay(1000);

// 2. Move to the line and align sensors over it
tracker.studyTrack();
delay(1000);

// Ready for use
```

---

### 🔧 Notes

- If lighting or surface changes (e.g. different floor), **repeat the calibration**.
- The `getStudyTypes()` function can tell you if the module is in `IDLE`, `BACKGROUND`, or `TRACK` learning mode (values: 0, 1, 2).

---

# Calibration Guide: `studyBackground()` and `studyTrack()`

Proper calibration helps the RGB Line Follower distinguish the line from the background under varying lighting conditions. The module supports two types of learning modes:

## `studyBackground()`

Learns what the background (non-line) surface looks like. Each RGB sensor records the reflectance value of the surface it's facing.  
📌 **Use this while the robot is placed on the background**.

```cpp
tracker.studyBackground();
```

## `studyTrack()`

Learns what the track (line) looks like. Each RGB sensor records the reflectance value when directly above the line.  
📌 **Use this while the robot is positioned over the line**.

```cpp
tracker.studyTrack();
```

## Full Example Sequence

```cpp
tracker.begin();
tracker.setRGBColour(RGB_COLOUR_GREEN);  // Optional indicator
delay(1000);

// Step 1: Calibrate background
tracker.studyBackground();
delay(1000);

// Step 2: Move robot over the line
tracker.studyTrack();
delay(1000);
```

## `getStudyTypes()`

You can check which mode the module is in:
- `0` = Idle  
- `1` = Learning background  
- `2` = Learning track  

Use this to confirm that the module accepted the calibration command.

---

# Summary Table of Public Functions

| Function | Description | Return Type |
|---------|-------------|-------------|
| `begin()` | Initializes I2C communication and prepares the device | `void` |
| `setpin(AD0, INT)` | Sets the I2C address selector pins manually | `void` |
| `loop()` | Efficiently calls sensor update every 8 ms to avoid I2C overload | `void` |
| `updataAllSensorValue()` | Manually triggers a full sensor value update over I2C | `void` |
| `getADCValueRGB1()` – `RGB4()` | Returns raw ADC value (0–255) of RGB sensors 1–4 | `uint8_t` |
| `getPositionOffset()` | Returns offset from center line (–512 to +512) | `int16_t` |
| `getPositionState()` | Returns bitmask of which sensors detect the line (0–15) | `uint8_t` |
| `setKp(value)` | Sets proportional gain (0.0–1.0) for line offset calculation | `void` |
| `setBackgroundThreshold(ch, value)` | Sets background detection threshold for sensor `ch` (0–3) | `int8_t` |
| `setTrackThreshold(ch, value)` | Sets track detection threshold for sensor `ch` (0–3) | `int8_t` |
| `getBackgroundThreshold(ch)` | Returns current background threshold for sensor `ch` | `uint8_t` |
| `getTrackThreshold(ch)` | Returns current track threshold for sensor `ch` | `uint8_t` |
| `setRGBColour(colour)` | Sets RGB LED color (RED, GREEN, BLUE) | `int8_t` |
| `getFirmwareVersion(buffer)` | Writes firmware version (8 bytes) into provided buffer | `void` |
| `getStudyTypes()` | Returns learning mode status: Idle (0), Background (1), Track (2) | `uint8_t` |
| `studyBackground()` | Starts background learning process | `int8_t` |
| `studyTrack()` | Starts track learning process | `int8_t` |


## Notes:
- `ch` for thresholds = `0` to `3` for RGB1 to RGB4.
- `colour` is one of: `RGB_COLOUR_RED`, `RGB_COLOUR_GREEN`, `RGB_COLOUR_BLUE`.


---
