Little Robot

What’s new

2 unread
  • New

    Little Robot Library Updates

    New versions of Barigadam_MotionSensor, Barigadam_ColorSensor, and LittleRobot are now available. We recommend installing the latest versions in Arduino IDE. Downloads and installation instructions are available below.

    View installation instructions
  • New

    Course updates, all in one place

    Library updates, new sections, and learning materials will appear here. Open the bell to see what’s new.

    View update history
All updates →

Library Functions Reference

Functions for controlling the robot and its sensors. How to Install Libraries.

Results: 82

LittleRobotLibrary

53 functions

Controls motors, encoders, line sensors, and robot movement.

Setup
#include <LittleRobot.h>

LittleRobot robot;

Core functions

robot.begin(invertEncoder1, invertEncoder2, wireClock)

Initialize the robot

Signature
void begin(
  bool invertEncoder1 = true,
  bool invertEncoder2 = true,
  unsigned long wireClock = 400000UL
);
Arguments
ArgumentDescription
invertEncoder1Invert encoder 1 if counts run backwards (default true)
invertEncoder2Same for encoder 2 (default true)
wireClockI2C speed in Hz (default 400000)
How it works

Initializes motors, button, LED, wheel encoders, and I2C.

Detailed description

Configures the four motor-control pins as outputs, the button as INPUT_PULLUP, and the LED as an output. It starts both encoders, clears their counters, calls Wire.begin(), and sets the I²C clock. Call it once in setup() before using the other library methods.

robot.MotorsMoveSync(speed_0, speed_1, enc_1, enc_2)

Drive two motors synchronously by encoder distance

Signature
void MotorsMoveSync(float speed_0, float speed_1, float enc_1, float enc_2);
Arguments
ArgumentDescription
speed_0Start speed 0–100
speed_1Cruise speed 0–100
enc_1Encoder degrees for ramp
enc_2Encoder degrees at cruise
Settings before the short call
robot.MotorsMoveSync_Settings.stop = 1;
robot.MotorsMoveSync_Settings.dir = 1;

robot.MotorsMoveSync(speed_0, speed_1, enc_1, enc_2);
What the settings change
stop= 1
Controls whether the function brakes after completion.
dir= 1
Controls forward or reverse movement.

Without robot.MotorsMoveSync_Settings_Save(), these changes apply only to the next short call.

How it works

Both motors forward: ramp, cruise, optional stop.

Detailed description

Clears both encoders, accelerates smoothly from speed_0 to speed_1 over enc_1 degrees, then travels another enc_2 degrees at working speed. During the move it compares the encoders and adjusts the left and right motor commands with PD correction. The short overload reads stop and dir from MotorsMoveSync_Settings and restores the saved settings afterward.

robot.Rotate(speed_0, speed_1, enc_1, enc_2)

Turn in place using encoders

Signature
void Rotate(float speed_0, float speed_1, float enc_1, float enc_2);
Arguments
ArgumentDescription
speed_0Starting speed.
speed_1Motor speed command.
enc_1Encoder distance used for acceleration.
enc_2Encoder distance at working speed.
Settings before the short call
robot.Rotate_Settings.stop = 1;
robot.Rotate_Settings.clockwise = 1;
robot.Rotate_Settings.to_line = 0;

robot.Rotate(speed_0, speed_1, enc_1, enc_2);
What the settings change
stop= 1
Controls whether the function brakes after completion.
clockwise= 1
Controls clockwise or counterclockwise rotation.
to_line= 0
Controls whether the robot continues turning until it detects a line.

Without robot.Rotate_Settings_Save(), these changes apply only to the next short call.

How it works

Turn in place. enc_2 = rotation amount in encoder degrees.

Detailed description

Clears the encoders, accelerates the motors in opposite directions, synchronizes their rotation, and then maintains working speed. With to_line == 1, it uses sensor 3 for clockwise == 1 or sensor 2 for the opposite direction and waits for the threshold sequence 200, 100, 120. With stop == 1, it calls MotorsStop() using opposite speed signs. The short overload uses Rotate_Settings and restores the saved values afterward.

robot.Turn_One(motor, speed_0, speed_1, enc_1, enc_2)

Pivot around one stopped wheel

Signature
void Turn_One(int motor, float speed_0, float speed_1, float enc_1, float enc_2);
Arguments
ArgumentDescription
motorMotor that turns: 1 or 2
speed_0Starting speed.
speed_1Motor speed command.
enc_1Encoder distance used for acceleration.
enc_2Encoder distance at working speed.
Settings before the short call
robot.Turn_One_Settings.stop = 1;
robot.Turn_One_Settings.dir = 1;

robot.Turn_One(motor, speed_0, speed_1, enc_1, enc_2);
What the settings change
stop= 1
Controls whether the function brakes after completion.
dir= 1
Controls forward or reverse movement.

Without robot.Turn_One_Settings_Save(), these changes apply only to the next short call.

How it works

Pivot: one motor turns, the other is held stopped.

Detailed description

First holds the second motor with MotorStop(), clears the selected motor's encoder, accelerates it over enc_1, and continues for another enc_2 degrees. With stop == 1, it stops the selected motor precisely using encoder feedback. The short overload uses Turn_One_Settings and restores the saved settings afterward.

robot.PD_Enc(speed, degrees, kp, kd)

Follow a line for a specified encoder distance

Signature
void PD_Enc(float speed, int degrees, float kp, float kd);
Arguments
ArgumentDescription
speedForward speed 0–100
degreesEncoder degrees to travel
kpPD controller gains
kdPD controller gains
Settings before the short call
robot.PD_Enc_Settings.stop = 1;
robot.PD_Enc_Settings.restriction = 0.1;
robot.PD_Enc_Settings.sensors = 23;
robot.PD_Enc_Settings.s_align = 25;
robot.PD_Enc_Settings.degrees_align = 150;
robot.PD_Enc_Settings.kp_align = 0.3;
robot.PD_Enc_Settings.kd_align = 1.0;
robot.PD_Enc_Settings.restrict_align = -0.2;

robot.PD_Enc(speed, degrees, kp, kd);
What the settings change
stop= 1
Controls whether the function brakes after completion.
restriction= 0.1
Limits the controller correction.
sensors= 23
Selects the line-sensor pair.
s_align= 25
Saved s_align setting used by the short function call.
degrees_align= 150
Saved degrees_align setting used by the short function call.
kp_align= 0.3
Saved kp_align setting used by the short function call.
kd_align= 1.0
Saved kd_align setting used by the short function call.
restrict_align= -0.2
Saved restrict_align setting used by the short function call.

Without robot.PD_Enc_Settings_Save(), these changes apply only to the next short call.

How it works

Follow line for a fixed encoder distance (sensors 2 & 3).

Detailed description

Clears the encoders. If degrees_align is positive, it first aligns using the selected sensor pair. It then drives to the total distance degrees, calculating error from the difference between the chosen sensors and correcting motor speed with a PD controller. Alignment distance is included in degrees. Use only sensor codes 23, 12, or 34. The short overload uses PD_Enc_Settings and restores them afterward.

robot.PD_Cross(speed, degrees, kp, kd)Blocking function

Follow a line to an intersection after a minimum distance

Signature
void PD_Cross(float speed, int degrees, float kp, float kd);
Arguments
ArgumentDescription
speedMotor speed command.
degreesTarget encoder distance in degrees.
kpProportional controller coefficient.
kdDerivative controller coefficient.
Settings before the short call
robot.PD_Cross_Settings.stop = 1;
robot.PD_Cross_Settings.restriction = 0.1;
robot.PD_Cross_Settings.sensors = 23;
robot.PD_Cross_Settings.go_to = 1234;
robot.PD_Cross_Settings.s_align = 25;
robot.PD_Cross_Settings.degrees_align = 150;
robot.PD_Cross_Settings.kp_align = 0.3;
robot.PD_Cross_Settings.kd_align = 1.0;
robot.PD_Cross_Settings.restrict_align = -0.2;

robot.PD_Cross(speed, degrees, kp, kd);
What the settings change
stop= 1
Controls whether the function brakes after completion.
restriction= 0.1
Limits the controller correction.
sensors= 23
Selects the line-sensor pair.
go_to= 1234
Selects the intersection pattern to detect.
s_align= 25
Saved s_align setting used by the short function call.
degrees_align= 150
Saved degrees_align setting used by the short function call.
kp_align= 0.3
Saved kp_align setting used by the short function call.
kd_align= 1.0
Saved kd_align setting used by the short function call.
restrict_align= -0.2
Saved restrict_align setting used by the short function call.

Without robot.PD_Cross_Settings_Save(), these changes apply only to the next short call.

How it works

Follow line until a crossing pattern is detected.

Detailed description

Uses the same line PD control as PD_Enc(), but continues until both conditions are true: the average encoder distance has reached degrees, and Intersection_Check(go_to) returns 1. Therefore degrees is a minimum distance, not a maximum. If the required intersection never appears, the function continues without a timeout. The short overload uses and restores PD_Cross_Settings.

robot.Intersection_Check(go_to)

Check an intersection pattern

Signature
int Intersection_Check(int go_to);
Arguments
ArgumentDescription
go_to1234, 123, 124, 134, 234, 12, or 34
How it works

Returns 1 if required sensors see the line (reading < 150).

Detailed description

Calls readLight() for every sensor named by the digits in the pattern code and compares each reading with the fixed threshold 150. It does not require the remaining sensors to be over a white surface.

Returns
ValueMeaning
Result1 when every requested sensor is below the threshold; otherwise 0.
robot.Turn_Gyro(speed_1, degrees_1)

Turn by a relative Motion Sensor angle

Signature
void Turn_Gyro(float speed_1, float degrees_1);
Arguments
ArgumentDescription
speed_1Motor speed command.
degrees_1Relative target angle in degrees.
Settings before the short call
robot.Turn_Gyro_Settings.addr = 0x60;
robot.Turn_Gyro_Settings.restriction = 0.9;
robot.Turn_Gyro_Settings.error_ok = 1.0;
robot.Turn_Gyro_Settings.error_slow = 30;
robot.Turn_Gyro_Settings.speed_min_slow = 20;
robot.Turn_Gyro_Settings.speed_max_slow = 25;

robot.Turn_Gyro(speed_1, degrees_1);
What the settings change
addr= 0x60
I²C address of the Motion Sensor.
restriction= 0.9
Limits the controller correction.
error_ok= 1.0
Saved error_ok setting used by the short function call.
error_slow= 30
Saved error_slow setting used by the short function call.
speed_min_slow= 20
Saved speed_min_slow setting used by the short function call.
speed_max_slow= 25
Saved speed_max_slow setting used by the short function call.

Without robot.Turn_Gyro_Settings_Save(), these changes apply only to the next short call.

How it works

Turn in place by adding degrees_1 to current yaw.

Detailed description

Reads the initial Yaw, adds degrees_1, and rotates the motors in opposite directions with an internal 0.3/0.3 PD controller. Completion requires more than ten consecutive iterations with error below error_ok, after which MotorsBrake_PD(addr) is called. The implementation does not normalize angles across the Yaw range boundary. An incorrect address can prevent completion. The short overload uses and restores Turn_Gyro_Settings.

robot.Go_Gyro(speed, degrees)

Drive straight while holding the initial heading

Signature
void Go_Gyro(float speed, float degrees);
Arguments
ArgumentDescription
speedMotor speed command.
degreesTarget encoder distance in degrees.
Settings before the short call
robot.Go_Gyro_Settings.kp = 7;
robot.Go_Gyro_Settings.kd = 70;
robot.Go_Gyro_Settings.stop = 1;
robot.Go_Gyro_Settings.direction = 1;
robot.Go_Gyro_Settings.addr = 0x60;

robot.Go_Gyro(speed, degrees);
What the settings change
kp= 7
Proportional controller coefficient.
kd= 70
Derivative controller coefficient.
stop= 1
Controls whether the function brakes after completion.
direction= 1
Controls forward or reverse movement.
addr= 0x60
I²C address of the Motion Sensor.

Without robot.Go_Gyro_Settings_Save(), these changes apply only to the next short call.

How it works

Drive straight for encoder degrees while holding initial heading.

Detailed description

Stores the initial Yaw, clears the encoders, and drives to degrees. On each iteration it multiplies heading error by direction, adjusts both motor commands with a PD controller, and limits them to -speed…speed. With stop == 1, it brakes precisely using the encoders and Yaw. The short overload uses and restores Go_Gyro_Settings.

robot.readLight(sensor)

Read a calibrated line sensor

Signature
float readLight(int sensor);
Arguments
ArgumentDescription
sensorSensor 1–4
How it works

Calibrated value 0–255 (0 black, 255 white).

Detailed description

Reads analogRead() from the sensor pin, maps the calibrated black…white range to 0…255, and constrains the result. Arduino's integer map() performs the conversion even though the method returns float. If black and white are equal, the raw value is simply constrained to 0…255.

Returns
ValueMeaning
ResultCalibrated value from 0 to 255; an invalid sensor number returns 0.

Motor control and braking

robot.MotorStart(motor, speed_1)

Control one motor directly

Signature
void MotorStart(int motor, float speed_1);
Arguments
ArgumentDescription
motor1 or 2
speed_1Motor speed command.
How it works

Runs one motor. Speed −100…100.

Detailed description

Constrains speed to -100…100. A magnitude from 1 to 100 maps to PWM 20…255, so the smallest non-zero command immediately uses PWM 20. A value strictly between -0.5 and 0.5 sets both inputs of the selected motor to 0, producing a free stop without active braking.

robot.MotorsStop(speed_1, speed_2)

Stop both motors with reverse drive and active braking

Signature
void MotorsStop(float speed_1, float speed_2);
Arguments
ArgumentDescription
speed_1Motor speed command.
speed_2Second motor speed command.
Settings before the short call
robot.MotorsStop_Settings.ms_1 = 120;
robot.MotorsStop_Settings.ms_2 = 30;

robot.MotorsStop(speed_1, speed_2);
What the settings change
ms_1= 120
Saved ms_1 setting used by the short function call.
ms_2= 30
Saved ms_2 setting used by the short function call.

Without robot.MotorsStop_Settings_Save(), these changes apply only to the next short call.

How it works

Stops both motors with active brake (default timing from settings).

Detailed description

First drives both motors with opposite speed signs for ms_1, then sets both inputs of each H-bridge to PWM 255 for ms_2, and finally calls MotorStart(..., 0) for a free stop. The short overload uses MotorsStop_Settings.ms_1/ms_2 and restores the saved settings.

robot.MotorStop(motor)

Stop one motor precisely using its encoder

Signature
void MotorStop(int motor);
Arguments
ArgumentDescription
motor1 or 2
How it works

Stops one motor using encoder feedback.

Detailed description

Stores the current encoder angle and uses an internal 4/30 PD controller to return the motor to that position. It finishes when the error stays within approximately ±5° for more than 60 ms, then sets both inputs of that motor to 255 for active braking. There is no timeout.

robot.MotorsBrake()

Apply active braking to both motors immediately

Arguments

No arguments.

How it works

Instant short-brake on both motors.

Detailed description

Sets both control inputs of each motor to PWM 255. It does not use encoders, wait for stabilization, or return the outputs to zero.

robot.MotorsBrake_PD()Blocking function

Brake precisely using encoders and the Motion Sensor

Signature
void MotorsBrake_PD();

void MotorsBrake_PD(uint8_t addr);
Arguments
ArgumentDescription
addrSensor I²C address.
Settings before the short call
robot.MotorsBrake_PD_Settings.addr = 0x60;
robot.MotorsBrake_PD_Settings.degree_error = 2.0;
robot.MotorsBrake_PD_Settings.yaw_error = 2.0;
robot.MotorsBrake_PD_Settings.degree_time = 60;
robot.MotorsBrake_PD_Settings.yaw_time = 30;

robot.MotorsBrake_PD();
What the settings change
addr= 0x60
I²C address of the Motion Sensor.
degree_error= 2.0
Saved degree_error setting used by the short function call.
yaw_error= 2.0
Saved yaw_error setting used by the short function call.
degree_time= 60
Saved degree_time setting used by the short function call.
yaw_time= 30
Saved yaw_time setting used by the short function call.

Without robot.MotorsBrake_PD_Settings_Save(), these changes apply only to the next short call.

How it works

Stop while holding heading with Motion Sensor (addr 0x60 by default).

Detailed description

Stores both encoder angles and the initial Yaw. Two independent PD controllers hold the wheels near their starting positions until the degree_error/degree_time conditions are met. It then restores the original heading with opposite motor commands and waits for yaw_error/yaw_time, finally calling MotorsBrake(). The zero-argument and address-only overloads use saved settings and restore them afterward. Missing feedback can block the function because there is no timeout.

Line sensors and calibration

robot.setLightCalibration(sensor, blackValue, whiteValue)

Set line-sensor calibration

Signature
void setLightCalibration(uint8_t sensor, int blackValue, int whiteValue);
Arguments
ArgumentDescription
sensorSensor 1–4
blackValueReading on black
whiteValueReading on white
How it works

Sets calibration for one sensor.

Detailed description

Changes the black and white calibration points for the selected logical sensor without changing its physical pin. An invalid sensor number outside 1…4 is ignored. The eight-argument overload rearranges physical-pin order into the library's logical order: sensor 1=A8, 2=A9, 3=A6, and 4=A7.

robot.setLightCalibration(blackA6…whiteA9)

Set line-sensor calibration

Signature
void setLightCalibration(
  int blackA6, int blackA7, int blackA8, int blackA9,
  int whiteA6, int whiteA7, int whiteA8, int whiteA9
);
Arguments
ArgumentDescription
blackA6, blackA7, blackA8, blackA9Value passed through the blackA6, blackA7, blackA8, blackA9 argument.
whiteA6, whiteA7, whiteA8, whiteA9Value passed through the whiteA6, whiteA7, whiteA8, whiteA9 argument.
How it works

Calibrates sensors using physical pins A6–A9 (as in Serial monitor).

robot.setLightCalibrationSensors(black1…white4)

Calibrate four sensors in logical order

Signature
void setLightCalibrationSensors(
  int black1, int black2, int black3, int black4,
  int white1, int white2, int white3, int white4
);
Arguments
ArgumentDescription
black1…black4Value passed through the black1…black4 argument.
white1…white4Value passed through the white1…white4 argument.
How it works

Calibrates sensors 1–4 in the order used by readLight().

robot.resetLightCalibration()

Reset line-sensor calibration

Arguments

No arguments.

How it works

Restores default calibration (~400 black, ~950 white).

robot.readLightRaw(sensor)

Read a raw line-sensor value

Signature
int readLightRaw(int sensor);
Arguments
ArgumentDescription
sensorSensor 1–4
How it works

Raw analog value for sensor 1–4.

Returns
ValueMeaning
результат analogRead() выбранного пина; при недопустимом номереRaw analogRead() value; an invalid sensor number returns 0.

Button and LED

robot.waitButtonPressRelease()

Wait for a complete button press and release

Arguments

No arguments.

How it works

Waits for a full button press and release before continuing.

Detailed description

Blocks while the button input is HIGH, waits 20 ms, then blocks until it returns to HIGH and waits another 20 ms. The button uses the internal pull-up, so a press reads LOW. There is no timeout.

robot.LED(state)

Control the robot's built-in LED

Signature
void LED(int state);
Arguments
ArgumentDescription
state1 = on, anything else = off
How it works

Turns the onboard LED on or off.

Encoders through the LittleRobot object

robot.getCounts(m)

Read an encoder counter

Arguments
ArgumentDescription
mEncoder number: 1 or 2.
How it works

Raw encoder ticks for motor m (1 or 2).

Returns
ValueMeaning
ResultSigned encoder count as long.
robot.getDegrees(m)

Read an encoder angle

Arguments
ArgumentDescription
mEncoder number: 1 or 2.
How it works

Encoder angle in degrees.

Returns
ValueMeaning
ResultEncoder angle in degrees as float.
robot.resetEncoder(m)

Reset one encoder

Arguments
ArgumentDescription
mEncoder number: 1 or 2.
How it works

Zero counter for motor m.

robot.resetAllEncoders()

Reset both encoders

Arguments

No arguments.

How it works

Zero both counters.

robot.setCPR(cpr)

Set encoder counts per revolution

Arguments
ArgumentDescription
cprCounts per revolution
How it works

Sets counts per wheel revolution.

Detailed description

Stores the supplied positive value. If cpr <= 0, it restores the default value 1415.

Saving and restoring settings

Short movement-function overloads read their values from the public *_Settings object. After the call finishes, the matching reset*() method restores the saved copy. A field changed without *_Settings_Save() affects only the next short call; saving it makes the new value persistent.

robot.MotorsStop_Settings_Save()

Motors Stop Settings Save

Arguments

No arguments.

How it works

Saves the current fields of this settings object as the persistent values used by the corresponding short function call.

robot.MotorsBrake_PD_Settings_Save()

Motors Brake PD Settings Save

Arguments

No arguments.

How it works

Saves the current fields of this settings object as the persistent values used by the corresponding short function call.

robot.MotorsMoveSync_Settings_Save()

Motors Move Sync Settings Save

Arguments

No arguments.

How it works

Saves the current fields of this settings object as the persistent values used by the corresponding short function call.

robot.Rotate_Settings_Save()

Rotate Settings Save

Arguments

No arguments.

How it works

Saves the current fields of this settings object as the persistent values used by the corresponding short function call.

robot.Turn_One_Settings_Save()

Turn One Settings Save

Arguments

No arguments.

How it works

Saves the current fields of this settings object as the persistent values used by the corresponding short function call.

robot.PD_Enc_Settings_Save()

PD Enc Settings Save

Arguments

No arguments.

How it works

Saves the current fields of this settings object as the persistent values used by the corresponding short function call.

robot.PD_Cross_Settings_Save()

PD Cross Settings Save

Arguments

No arguments.

How it works

Saves the current fields of this settings object as the persistent values used by the corresponding short function call.

robot.Turn_Gyro_Settings_Save()

Turn Gyro Settings Save

Arguments

No arguments.

How it works

Saves the current fields of this settings object as the persistent values used by the corresponding short function call.

robot.Go_Gyro_Settings_Save()

Go Gyro Settings Save

Arguments

No arguments.

How it works

Saves the current fields of this settings object as the persistent values used by the corresponding short function call.

robot.AllSettings_Save()

All Settings Save

Arguments

No arguments.

How it works

Saves the current fields of every settings object as the persistent values used by short function calls.

Detailed description

Saves the current fields of every settings object as the persistent values used by short function calls. The implementation uses the limits, return values, and error behavior documented in the signature and argument table above.

robot.resetMotorsStop_Settings()

Reset Motors Stop Settings

Arguments

No arguments.

How it works

Restores this public settings object from the values saved for the corresponding function.

robot.resetMotorsBrake_PD_Settings()

Reset Motors Brake PD Settings

Arguments

No arguments.

How it works

Restores this public settings object from the values saved for the corresponding function.

robot.resetMotorsMoveSync_Settings()

Reset Motors Move Sync Settings

Arguments

No arguments.

How it works

Restores this public settings object from the values saved for the corresponding function.

robot.resetRotate_Settings()

Reset Rotate Settings

Arguments

No arguments.

How it works

Restores this public settings object from the values saved for the corresponding function.

robot.resetTurn_One_Settings()

Reset Turn One Settings

Arguments

No arguments.

How it works

Restores this public settings object from the values saved for the corresponding function.

robot.resetPD_Enc_Settings()

Reset PD Enc Settings

Arguments

No arguments.

How it works

Restores this public settings object from the values saved for the corresponding function.

robot.resetPD_Cross_Settings()

Reset PD Cross Settings

Arguments

No arguments.

How it works

Restores this public settings object from the values saved for the corresponding function.

robot.resetTurn_Gyro_Settings()

Reset Turn Gyro Settings

Arguments

No arguments.

How it works

Restores this public settings object from the values saved for the corresponding function.

robot.resetGo_Gyro_Settings()

Reset Go Gyro Settings

Arguments

No arguments.

How it works

Restores this public settings object from the values saved for the corresponding function.

robot.resetAllSettings()

Reset All Settings

Arguments

No arguments.

How it works

Restores every public settings object from its saved persistent values.

Detailed description

Restores every public settings object from its saved persistent values. The implementation uses the limits, return values, and error behavior documented in the signature and argument table above.

Default settings fields

These are not functions, but they supply the arguments used by the short overloads and are important for understanding their behavior. - MotorsStop_Settings: ms_1=120, ms_2=30. - MotorsBrake_PD_Settings: addr=0x60, degree_error=2.0, yaw_error=2.0, degree_time=60, yaw_time=30. - MotorsMoveSync_Settings: stop=1, dir=1. - Rotate_Settings: stop=1, clockwise=1, to_line=0. - Turn_One_Settings: stop=1, dir=1. - PD_Enc_Settings: stop=1, restriction=0.1, sensors=23, s_align=25, degrees_align=150, kp_align=0.3, kd_align=1.0, restrict_align=-0.2. - PD_Cross_Settings: the same fields plus go_to=1234. - Turn_Gyro_Settings: addr=0x60, restriction=0.9, error_ok=1.0, error_slow=30, speed_min_slow=20, speed_max_slow=25. - Go_Gyro_Settings: kp=7, kd=70, stop=1, direction=1, addr=0x60.

Low-level global encoder functions

These functions are declared in DualEncodersMega.h and are available because LittleRobot.h includes that header. In a normal sketch, prefer the robot.* methods so that the two interfaces are not mixed.

encodersBegin(invert1, invert2)

Initialize the low-level encoder interface

Arguments
ArgumentDescription
invert1Reverse the sign of encoder 1
invert2Reverse the sign of encoder 2
How it works

Configures the Arduino Mega encoder pins, starts their interrupts, and resets both counters.

Detailed description

Disables interrupts, configures pins 19/3 and 18/2 as INPUT_PULLUP, reads the initial quadrature-channel states, attaches external interrupts INT2–INT5 on signal changes, clears both counters, and enables interrupts again.

getCounts(m)

Read a global encoder counter

Arguments
ArgumentDescription
mEncoder number: 1 or 2
How it works

Atomically returns the signed tick count for encoder 1 or 2.

Returns
ValueMeaning
ResultSigned global encoder count as long.
getDegrees(m)

Read a global encoder angle

Arguments
ArgumentDescription
mEncoder number: 1 or 2
How it works

Converts the selected encoder count to degrees using the current CPR value.

Returns
ValueMeaning
ResultGlobal encoder angle in degrees as float.
resetEncoder(m)

Reset one global encoder

Arguments
ArgumentDescription
mEncoder number: 1 or 2
How it works

Atomically sets the selected global encoder counter to zero.

resetAllEncoders()

Reset both global encoders

Arguments

No arguments.

How it works

Atomically sets both global encoder counters to zero.

setCPR(cpr)

Set the global counts-per-revolution value

Arguments
ArgumentDescription
cprCounts per wheel revolution
How it works

Stores a positive CPR value; zero or a negative value restores the default of 1415.

Detailed description

Stores a positive value in the global CPR variable. Zero or a negative value restores the constant 1415.

Barigadam_MotionSensor

19 functions

Orientation, calibration, and motion sensor settings

#include <Barigadam_MotionSensor.h>

Getting started

The library reads the motion sensor's rotation and tilt. Here, sensor is the sensor object at address 0x60. Call Wire.begin() once in setup() to start communication; when using LittleRobot, robot.begin() starts it.

#include <Wire.h>
#include <Barigadam_MotionSensor.h>

BarigadamMotionSensor sensor(0x60);

void setup() {
  Serial.begin(9600);
  Wire.begin();
}

void loop() {
  float yaw, pitch, roll;
  if (sensor.readYPR(yaw, pitch, roll)) {
    Serial.print(yaw);
    Serial.print(" ");
    Serial.print(pitch);
    Serial.print(" ");
    Serial.println(roll);
  } else {
    Serial.println("I2C error");
  }
  delay(100);
}

BarigadamMotionSensor sensor(address)create a sensor object

How it works

Creates an object that communicates with the sensor at the specified address. The device's address is unchanged. Declare the object before setup().

Scroll sideways to see all columns.

Arguments
ArgumentPurposeAccepted values
addressThe connected sensor's address.From 0x40 to 0x60, inclusive. Default: 0x60.
BarigadamMotionSensor sensor(0x60);

Angles in degrees

sensor.readYPR(yaw, pitch, roll)read three angles

How it works

Reads three angles in one request and writes them to the variables. Check the result to distinguish zero angles from a communication error.

Scroll sideways to see all columns.

Arguments
ArgumentPurposeAccepted values
yawOutput variable: rotation around the vertical axis.A float variable; angle in degrees.
pitchOutput variable: forward/backward tilt.A float variable; angle in degrees.
rollOutput variable: side-to-side tilt.A float variable; angle in degrees.
ResultMeaning
trueThe readings were written to the variables.
falseReading failed; all output variables are zero.
float yaw, pitch, roll;
if (sensor.readYPR(yaw, pitch, roll)) {
  Serial.println(yaw);
}

sensor.getYaw()rotation around the vertical axis

How it works

Returns rotation around the vertical axis in degrees. A communication error also returns 0; use readYPR() when you need to check whether reading succeeded.

float yaw = sensor.getYaw();
Serial.println(yaw);

sensor.getPitch()forward/backward tilt

How it works

Returns forward/backward tilt in degrees. A communication error also returns 0; use readYPR() when you need to check whether reading succeeded.

float pitch = sensor.getPitch();
Serial.println(pitch);

sensor.getRoll()side-to-side tilt

How it works

Returns side-to-side tilt in degrees. A communication error also returns 0; use readYPR() when you need to check whether reading succeeded.

float roll = sensor.getRoll();
Serial.println(roll);

Zero reset and calibration

sensor.zeroReset()reset angles to zero

How it works

Sends a command to use the current orientation as zero. The result confirms transmission, not completion of the reset.

ResultMeaning
trueThe I²C command was acknowledged.
falseThe command failed: check the arguments, address, and connection.
if (!sensor.zeroReset()) {
  Serial.println("I2C error");
}

sensor.calibrate100()quick calibration

How it works

Starts quick gyroscope calibration. Keep the sensor still until it finishes. The call does not wait for calibration; true only confirms transmission.

ResultMeaning
trueThe I²C command was acknowledged.
falseThe command failed: check the arguments, address, and connection.
if (!sensor.calibrate100()) {
  Serial.println("I2C error");
}

sensor.calibrate500()full calibration

How it works

Starts full gyroscope calibration. Keep the sensor still until it finishes. The call does not wait for calibration; true only confirms transmission.

ResultMeaning
trueThe I²C command was acknowledged.
falseThe command failed: check the arguments, address, and connection.
if (!sensor.calibrate500()) {
  Serial.println("I2C error");
}

Raw angles and registers

sensor.readYPRRaw(yaw, pitch, roll)three angles in tenths of a degree

How it works

Reads three angles in one request without converting them to fractional degrees. For example, 125 means 12.5°. Returns false and clears the variables on failure.

Scroll sideways to see all columns.

Arguments
ArgumentPurposeAccepted values
yawOutput variable: rotation around the vertical axis.An int16_t variable; each unit is 0.1°.
pitchOutput variable: forward/backward tilt.An int16_t variable; each unit is 0.1°.
rollOutput variable: side-to-side tilt.An int16_t variable; each unit is 0.1°.
ResultMeaning
trueThe readings were written to the variables.
falseReading failed; all output variables are zero.
int16_t yaw, pitch, roll;
if (sensor.readYPRRaw(yaw, pitch, roll)) {
  Serial.println(yaw);
}

sensor.getYawRaw()rotation around the vertical axis in tenths of a degree

How it works

Returns a signed integer: 10 represents 1°. An error also returns 0; use readYPRRaw() to check whether reading succeeded.

int16_t yaw = sensor.getYawRaw();
Serial.println(yaw);

sensor.getPitchRaw()forward/backward tilt in tenths of a degree

How it works

Returns a signed integer: 10 represents 1°. An error also returns 0; use readYPRRaw() to check whether reading succeeded.

int16_t pitch = sensor.getPitchRaw();
Serial.println(pitch);

sensor.getRollRaw()side-to-side tilt in tenths of a degree

How it works

Returns a signed integer: 10 represents 1°. An error also returns 0; use readYPRRaw() to check whether reading succeeded.

int16_t roll = sensor.getRollRaw();
Serial.println(roll);

sensor.readRegister(reg)read a register

How it works

Reads one byte from the specified sensor register. Returns a number from 0 to 255; an error also returns 0.

Scroll sideways to see all columns.

Arguments
ArgumentPurposeAccepted values
regRegister number.0x00–0xFF; the sensor firmware defines each register's meaning.

To read a complete angle, use getYaw(), getPitch(), getRoll(), or readYPR().

Address, mode, and correction

sensor.getAddress()object address

How it works

Returns the address this object uses to communicate with the sensor. Does not check the connection.

Serial.println(sensor.getAddress(), HEX);

sensor.changeAddress(newAddress)change the sensor address

How it works

Sends a new address to the sensor. After successful transmission, the object uses that address without checking for a response there. Connect only the sensor being configured and choose an unused address.

Scroll sideways to see all columns.

Arguments
ArgumentPurposeAccepted values
newAddressThe sensor's I²C address.0x40–0x60; must differ from the current address and be unused.
ResultMeaning
trueThe I²C command was acknowledged.
falseThe command failed: check the arguments, address, and connection.
if (sensor.changeAddress(0x41)) {
  Serial.println(sensor.getAddress(), HEX);
}

sensor.setMode(mode)display and button mode

How it works

Sets how the sensor's display and button work. I²C angle readings remain available in all three modes. Returns the command transmission result.

Scroll sideways to see all columns.

Arguments
ArgumentPurposeAccepted values
modeOperating mode.0, 1, 2.
ModeBehavior
0Display off.
1Display shows angles; button enabled.
2Display shows angles; button disabled.
ResultMeaning
trueThe I²C command was acknowledged.
falseThe command failed: check the arguments, address, and connection.
if (!sensor.setMode(1)) {
  Serial.println("I2C error");
}

sensor.setCourseCorrection(correction)course correction

How it works

Sends a coefficient that adjusts the measured rotation. Call saveCourseCorrection() to store it in the sensor's memory.

Scroll sideways to see all columns.

Arguments
ArgumentPurposeAccepted values
correctionCorrection coefficient.From 0.5 to 1.5, inclusive; dimensionless.
ResultMeaning
trueThe I²C command was acknowledged.
falseThe command failed: check the arguments, address, and connection.
if (!sensor.setCourseCorrection(1.02f)) {
  Serial.println("I2C error");
}

sensor.saveCourseCorrection()save course correction

How it works

Sends a command to store the correction coefficient in the sensor's memory. Returns true if transmission succeeds; it does not read the stored value back.

ResultMeaning
trueThe I²C command was acknowledged.
falseThe command failed: check the arguments, address, and connection.
if (sensor.setCourseCorrection(1.02f)) {
  if (!sensor.saveCourseCorrection()) {
    Serial.println("I2C error");
  }
}

Diagnostics

BarigadamMotionSensor::scanI2C()find I²C devices

How it works

Prints responding device addresses to the Serial Monitor. Checks addresses from 0x01 to 0x7E, then pauses for 5 seconds before repeating. The call never returns; use a separate diagnostic sketch.

#include <Wire.h>
#include <Barigadam_MotionSensor.h>

void setup() {
  Serial.begin(9600);
  Wire.begin();
  BarigadamMotionSensor::scanI2C();
}

void loop() {
}

Barigadam_ColorSensor

10 functions

Color recognition, RGBC, HSV, and sensor settings

#include <Barigadam_ColorSensor.h>

Getting started

The library reads recognized colors and the sensor's light channels. Here, sensor is an object at address 0x40. Call Wire.begin() once in setup(); with LittleRobot, robot.begin() starts communication.

#include <Wire.h>
#include <Barigadam_ColorSensor.h>

BarigadamColorSensor sensor(0x40);
bool sensorReady = false;

void setup() {
  Serial.begin(9600);
  Wire.begin();
  delay(20);
  sensorReady = sensor.setMode(1);
  if (!sensorReady) {
    Serial.println("I2C error");
  }
}

void loop() {
  if (!sensorReady) return;
  int color = sensor.readColor();
  if (color == -2) {
    Serial.println("I2C error");
  } else {
    Serial.println(color);
  }
  delay(200);
}

Create a separate object for each sensor. Devices on the same bus must have different addresses. Assign addresses with one sensor connected at a time.

BarigadamColorSensor leftSensor(0x40);
BarigadamColorSensor rightSensor(0x41);

BarigadamColorSensor sensor(address)create a sensor object

How it works

Creates an object that communicates with the sensor at the specified address. The device's address is unchanged. Declare the object before setup().

Scroll sideways to see all columns.

Arguments
ArgumentPurposeAccepted values
addressThe connected sensor's address.From 0x40 to 0x60, inclusive. Default: 0x40.
BarigadamColorSensor sensor(0x40);

Color and readings

sensor.readColor()read the recognized color

How it works

Returns the color number recognized by the sensor. Select mode 1 for standard recognition. Store the result in an int to retain negative codes.

ResultMeaning
1Black.
2Blue.
3Green.
4Yellow.
5Red.
6White.
-1Color not recognized.
-2I²C communication error.
int color = sensor.readColor();
if (color == -2) {
  Serial.println("I2C error");
} else if (color == -1) {
  Serial.println("Unknown color");
} else {
  Serial.println(color);
}

sensor.readRGBC(r, g, b, c)read RGBC channels

How it works

Reads the red, green, blue, and clear light channels in one request. Select mode 4 to inspect raw readings. Results are written to uint16_t variables.

Scroll sideways to see all columns.

Arguments
ArgumentPurposeAccepted values
r, g, bOutput variables for red, green, and blue channels.uint16_t variables: 0–65535, raw counts.
cOutput variable for the overall light level.A uint16_t variable: 0–65535, raw counts.
ResultMeaning
trueThe readings were written to the variables.
falseReading failed; all output variables are zero.
uint16_t r, g, b, c;
if (sensor.readRGBC(r, g, b, c)) {
  Serial.println(r);
  Serial.println(g);
  Serial.println(b);
  Serial.println(c);
}

Use sensor.readRGBC(channel) to get one channel. It returns 0 for an error or an invalid channel number.

Scroll sideways to see all columns.

Arguments
ArgumentPurposeAccepted values
channelChannel to read.1 — R; 2 — G; 3 — B; 4 — C.
uint16_t red = sensor.readRGBC(1);
Serial.println(red);

sensor.readHSV(h, s, v)hue, saturation, and brightness

How it works

Calculates three HSV values from one RGBC sample and writes them to float variables. If the clear channel is zero, all three values are zero and the read succeeds.

Scroll sideways to see all columns.

Arguments
ArgumentPurposeAccepted values
hOutput variable for hue.float: from 0° inclusive to 360° exclusive.
sOutput variable for saturation.float: 0 to 1, dimensionless.
vOutput variable for brightness.float: 0 to 1, dimensionless.
ResultMeaning
trueThe readings were written to the variables.
falseReading failed; all output variables are zero.
float h, s, v;
if (sensor.readHSV(h, s, v)) {
  Serial.println(h);
  Serial.println(s);
  Serial.println(v);
}

Use sensor.readHSV(channel) for one value. An error or an invalid channel number returns 0.

Scroll sideways to see all columns.

Arguments
ArgumentPurposeAccepted values
channelValue to read.1 — H; 2 — S; 3 — V.
float hue = sensor.readHSV(1);
Serial.println(hue);

Registers

sensor.readRegister(reg, value)read a register and check communication

How it works

Reads one byte from a register into value. Returns true on success. On failure, returns false and sets value to zero.

Scroll sideways to see all columns.

Arguments
ArgumentPurposeAccepted values
regRegister number.0x00–0xFF; 0x08 is the color code, 0x09 is the current mode.
valueOutput variable for the byte read.A uint8_t variable: 0 to 255.
uint8_t mode;
if (sensor.readRegister(0x09, mode)) {
  Serial.println(mode);
} else {
  Serial.println("I2C error");
}

The call sensor.readRegister(reg) returns the byte directly. In this form, 0 can mean either a valid reading or an error.

uint8_t mode = sensor.readRegister(0x09);
Serial.println(mode);

Mode and address

sensor.setMode(mode)select the sensor mode

How it works

Sends the mode command and returns to the program. true confirms I²C transmission. Read register 0x09 to check the current mode; persistence after power-off depends on the firmware.

Scroll sideways to see all columns.

Arguments
ArgumentPurposeAccepted values
modeSensor operating mode.An integer from 0 to 5.
ModePurpose
0Operation without indication.
1Basic color recognition.
2Recognition of colored objects only.
3True color mode.
4Raw RGBC readings.
5Ambient readings without illumination.
ResultMeaning
trueThe I²C command was acknowledged.
falseThe command failed: check the arguments, address, and connection.
if (!sensor.setMode(4)) {
  Serial.println("I2C error");
}

sensor.getAddress()object address

How it works

Returns the address this object uses to communicate with the sensor. Does not check the connection.

Serial.println(sensor.getAddress(), HEX);

sensor.changeAddress(newAddress)change the sensor address

How it works

Checks that the chosen address is unused and sends the change command. Then checks for a response at the new address, allowing up to 100 ms of delays plus I²C communication time. Updates the object's address when confirmed. Connect only the sensor being configured.

Scroll sideways to see all columns.

Arguments
ArgumentPurposeAccepted values
newAddressThe sensor's I²C address.0x40–0x60; must differ from the current address and be unused.
ResultMeaning
trueThe sensor responded at the new address; the object now uses it.
falseThe change was not confirmed; the object's address is unchanged. Check the device's actual address with the scanner.
if (sensor.changeAddress(0x41)) {
  Serial.println(sensor.getAddress(), HEX);
} else {
  Serial.println("Address change failed");
}

sensor.sendToSensor(dataToSend)configure with one command

How it works

Selects a mode or changes the address according to the value provided. Returns the result of setMode() or changeAddress() and continues the program.

Scroll sideways to see all columns.

Arguments
ArgumentPurposeAccepted values
dataToSendMode or address.0–5 selects a mode; 0x40–0x60 changes the address. Other values return false.
if (!sensor.sendToSensor(1)) {
  Serial.println("I2C error");
}

Diagnostics

BarigadamColorSensor::scanI2C()find I²C devices

How it works

Prints responding device addresses to the Serial Monitor. Checks addresses from 0x01 to 0x7E, then pauses for 5 seconds before repeating. The call never returns; use a separate diagnostic sketch.

BarigadamColorSensor::I2Cscan() performs the same scan.

#include <Wire.h>
#include <Barigadam_ColorSensor.h>

void setup() {
  Serial.begin(9600);
  Wire.begin();
  BarigadamColorSensor::scanI2C();
}

void loop() {
}