AntiprotonTechnologies

02Singularity Hub

Sensors, one by one

A robot only knows what its sensors tell it. Here we take each sensor alone: what it is, how far and how often it can measure, what its numbers mean, how to read it in plain Python and in ROS 2, and a small program to test it. Each test program has been run in Singularity, so if yours behaves differently, the difference is a clue.

Every sensor can be switched on and off in the Robot tab, and most have settings there (beams, range, noise and so on). The numbers below are the defaults.

All sensors at a glance

SensorMeasuresRangeHow oftenSimple callROS 2 topic
LiDARDistance all the way around0.12 – 3.5 m10 times/srobot.lidar()/scan
Ultrasonic (×6)One distance, in a cone0.02 – 2.0 m20 times/srobot.front_distance()/sonar/front …
CameraA color picture160 × 120 pixels, 70° wide15 times/srobot.camera()/camera/image_raw
IR line sensors (×5)Dark or light floor0 (floor) – 1 (tape)50 times/srobot.line_sensors()/line_sensors
IMUHeading, turn rate, acceleration−180° to 180°50 times/srobot.heading()/imu
Wheel encodersHow far each wheel turned360 ticks per turnevery steprobot.encoders()/wheel_ticks, /odom
GPSPosition in the world± about 2 cm10 times/srobot.position()/gps
BumperTouching something or notTrue / False20 times/srobot.bumped()/bumper

The spinning laser tape measure

LiDAR

A LiDAR spins a laser beam around and measures how far away things are in every direction. Think of it as a tape measure that goes all the way around the robot, ten times a second. It does not care about light, so it works in the dark.

Beams
360 (one per degree). Robot tab: 90 to 720
Range
from 0.12 m to 3.5 m. Robot tab: max 1 to 8 m
Speed
10 scans per second (1 to 20)
Noise
about ±1 cm (σ = 0.01 m)
Height
a flat slice 17.5 cm above the floor (Scout) or 21.5 cm (Ranger)

What the numbers mean

  • robot.lidar() gives a list of 360 distances in meters. Index 0 is straight ahead, and the index goes up as you turn left: 90 is the left side, 180 is behind, 270 is the right side.
  • robot.lidar_distance(90) is the reading at 90° (left). Use negative angles for the right: lidar_distance(-90).
  • inf (infinity) means nothing was hit within range, not “very close”. Remember this when you use min().
  • It only sees things that cross its beam height. A chair’s feet, a low step or a table top can be invisible to it. The ultrasonic sensors and the bumper help with those.
lidar_simple.pytested in the Playground
# LiDAR test · world: Playground
# robot.lidar() gives 360 distances in meters. Index 0 = straight ahead,
# then counter-clockwise: 90 = left, 180 = behind, 270 = right.
# inf means nothing within range (3.5 m).
robot.wait(0.2)                            # let the first scan arrive
while True:
    ranges = robot.lidar()
    front = robot.lidar_distance(0)
    left = robot.lidar_distance(90)
    right = robot.lidar_distance(-90)
    nearest = min(ranges)
    angle = ranges.index(nearest)          # degrees, because there are 360 beams
    print(f"front {front:.2f}  left {left:.2f}  right {right:.2f}  nearest {nearest:.2f} m at {angle}°")
    robot.turn_left(0.4)                   # spin slowly to see the numbers change
    robot.wait(0.5)

The same thing as a ROS 2 node. The message type is sensor_msgs/LaserScan; the angle of beam i is angle_min + i × angle_increment, in radians:

lidar_ros2.pytested
# LiDAR test, ROS 2 style · world: Playground
import math
import rclpy
from rclpy.node import Node
from sensor_msgs.msg import LaserScan

class LidarTest(Node):
    def __init__(self):
        super().__init__('lidar_test')
        self.create_subscription(LaserScan, '/scan', self.on_scan, 10)

    def on_scan(self, scan):
        # beam i points at angle_min + i * angle_increment (radians, 0 = forward)
        valid = [(r, i) for i, r in enumerate(scan.ranges) if scan.range_min < r < scan.range_max]
        if not valid:
            return
        r, i = min(valid)
        angle = math.degrees(scan.angle_min + i * scan.angle_increment)
        self.get_logger().info(f'{len(scan.ranges)} beams, nearest {r:.2f} m at {angle:.0f} deg')

rclpy.init()
rclpy.spin(LidarTest())

And in ROS 1 (rospy) style, if your course uses ROS 1:

lidar_ros1.pytested
# The same LiDAR test in ROS 1 (rospy) style · world: Playground
import rospy
from sensor_msgs.msg import LaserScan
from geometry_msgs.msg import Twist

def on_scan(scan):
    front = min(scan.ranges[-15:] + scan.ranges[:15])
    rospy.loginfo('front %.2f m', front)
    cmd = Twist()
    if front < 0.5:
        cmd.angular.z = 0.8
    else:
        cmd.linear.x = 0.2
    pub.publish(cmd)

rospy.init_node('lidar_test')
pub = rospy.Publisher('/cmd_vel', Twist, queue_size=10)
rospy.Subscriber('/scan', LaserScan, on_scan)
rospy.spin()

In real life: an RPLIDAR A1/A2, LD06/LD19 or YDLIDAR X4. They publish the same /scan message through their ROS 2 driver.

Like a bat

Ultrasonic sensors

An ultrasonic sensor clicks out a sound too high for us to hear and listens for the echo. The longer the echo takes, the further away the thing is. It gives one distance, from a cone in front of it, not a thin line.

Mounts
front, front-left, front-right, left, right are on; back is off (click its spot on the robot picture in the Robot tab)
Range
0.02 m to 2.0 m. Robot tab: max 0.5 to 4 m
Cone
30° wide (10° to 60°)
Speed
20 readings per second (5 to 40)
Noise
about ±0.5 cm
Height
6 cm above the floor (Scout), 11 cm (Ranger): lower than the LiDAR, so it sees low things

What the numbers mean

  • robot.front_distance(), front_left_distance(), front_right_distance(), left_distance(), right_distance(), back_distance(), or by name: robot.distance("front_left").
  • When nothing is in range, the simple commands give the maximum range (2.0). The ROS topics give inf instead, the way real ROS drivers do.
  • Sound bounces like light off a mirror. A wall hit at a steep angle can send the echo away, so the sensor reads 2.0 even though a wall is there (except very close, within about 25 cm). Real ultrasonic sensors do exactly this.
sonar_simple.pytested
# Ultrasonic test · world: Playground
# Five sensors are on by default (the back one is off: turn it on in the Robot tab).
# 2.0 = nothing within range.
robot.wait(0.1)
for _ in range(20):
    print("front", round(robot.front_distance(), 2),
          "| front-left", round(robot.front_left_distance(), 2),
          "| front-right", round(robot.front_right_distance(), 2),
          "| left", round(robot.left_distance(), 2),
          "| right", round(robot.right_distance(), 2))
    # the same thing by name: robot.distance("front_left")
    robot.wait(0.5)

ROS 2: each sensor has its own topic (/sonar/front, /sonar/front_left, …) with a sensor_msgs/Range message; the distance is msg.range.

sonar_ros2.pytested
# Ultrasonic test, ROS 2 style · world: Playground
# Each sensor has its own topic: /sonar/front, /sonar/front_left, /sonar/left ...
import rclpy
from rclpy.node import Node
from sensor_msgs.msg import Range

class SonarTest(Node):
    def __init__(self):
        super().__init__('sonar_test')
        self.latest = {}
        for name in ['front', 'front_left', 'front_right', 'left', 'right']:
            self.create_subscription(Range, f'/sonar/{name}',
                                     lambda msg, name=name: self.latest.__setitem__(name, msg.range), 10)
        self.create_timer(0.5, self.report)

    def report(self):
        self.get_logger().info('  '.join(f'{k} {v:.2f}' for k, v in self.latest.items()))

rclpy.init()
rclpy.spin(SonarTest())

In real life: the HC-SR04 (about $2) or the waterproof JSN-SR04T, read by an Arduino or a Raspberry Pi.

The robot’s eye

Camera

The camera gives a picture made of tiny colored dots called pixels. Each pixel has three numbers: how much red, green and blue it has, from 0 to 255. The camera needs light, just like your eyes: dim the room (World tab → Room lights) and it sees less, unless the headlights are on.

Picture
160 × 120 pixels (320 × 240 or 640 × 480 in the Robot tab)
Speed
15 pictures per second (5 to 30)
Field of view
70° wide (40° to 100°)
Mount
on a pan-tilt head on a short mast, starting tilted 40° down (Scout) or 38° (Ranger) to see the floor ahead

What the numbers mean

  • robot.camera() gives a NumPy array shaped (120, 160, 3): 120 rows, 160 columns, 3 colors. img[0, 0] is the top-left pixel; img[60, 80] is near the middle.
  • The camera switches on the first time you ask for a picture, so that very first call gives None. Wait a moment and ask again (the test program shows how).
  • robot.find_color("red") finds a colored thing for you. It knows red, orange, yellow, green, cyan, blue, purple, pink, black and white, or a hue range like (100, 140). It returns None if it sees nothing, or a dictionary:
    • x: −1 = left edge of the picture, 0 = middle, +1 = right edge
    • y: −1 = top, +1 = bottom
    • size: how much of the picture it covers, 0 to 1 (bigger = closer)
    • width, height: its size across and up, 0 to 1; pixels: how many pixels
camera_simple.pytested in the Camera Lab
# Camera test · world: Camera Lab
# robot.camera() is a NumPy image (120 rows, 160 columns, 3 colors).
# robot.find_color() finds a colored thing for you.
img = robot.camera()                       # the first call switches the camera on...
while img is None:                         # ...so wait for the first picture
    robot.wait(0.1)
    img = robot.camera()
print("image size:", img.shape, " average color:", img.reshape(-1, 3).mean(axis=0).round())
robot.tilt_camera(10)                      # look almost straight ahead (0 = level)
for angle in [60, 30, 0, -30, -60]:        # sweep the camera head left to right
    robot.pan_camera(angle)
    robot.wait(0.8)                        # the servo needs time to turn
    seen = robot.find_color("red")
    if seen:
        print(f"pan {angle:+} deg: red at x={seen['x']:.2f}, size={seen['size']:.3f}")
    else:
        print(f"pan {angle:+} deg: no red")
robot.pan_camera(0)

ROS 2 style: the message is sensor_msgs/Image (rgb8). Turn its bytes into a NumPy picture with np.frombuffer(msg.data, np.uint8).reshape(msg.height, msg.width, 3). Here we find red pixels ourselves:

camera_ros2.pytested: finds the red ball while turning
# Camera test, ROS 2 style · world: Camera Lab
# Find red pixels yourself with NumPy, the way you would with OpenCV on a real robot.
import numpy as np
import rclpy
from rclpy.node import Node
from sensor_msgs.msg import Image
from geometry_msgs.msg import Twist
from std_msgs.msg import Float64

class CameraTest(Node):
    def __init__(self):
        super().__init__('camera_test')
        self.create_subscription(Image, '/camera/image_raw', self.on_image, 10)
        self.pub = self.create_publisher(Twist, '/cmd_vel', 10)
        # the camera starts tilted 40 degrees down at the floor; raise it to 10 degrees
        tilt = self.create_publisher(Float64, '/camera/tilt', 1)
        tilt.publish(Float64(data=0.17))                # radians on topics (0.17 rad = 10 deg)

    def on_image(self, msg):
        img = np.frombuffer(msg.data, np.uint8).reshape(msg.height, msg.width, 3).astype(int)
        r, g, b = img[..., 0], img[..., 1], img[..., 2]
        red = (r > 120) & (r > g + 50) & (r > b + 50)
        if red.sum() > 20:
            cols = np.nonzero(red)[1]
            x = cols.mean() / msg.width * 2 - 1        # -1 = left edge, +1 = right edge
            self.get_logger().info(f'red: {red.sum()} pixels, centre x = {x:+.2f}')
        else:
            self.get_logger().info('no red in view')
        turn = Twist()
        turn.angular.z = 0.5                            # spin slowly to look around
        self.pub.publish(turn)

rclpy.init()
rclpy.spin(CameraTest())

In real life: a Raspberry Pi Camera Module or any USB webcam, with OpenCV for the image work.

Camera pan and tilt

The camera sits on two small servo motors, like a head that can look left and right (pan) and up and down (tilt).

CommandRangeStarts at
Pan (left / right)robot.pan_camera(degrees)−150° (right) to +150° (left); 0 = straight ahead0°
Tilt (down / up)robot.tilt_camera(degrees)+70° (down at the floor) to −25° (up); 0 = level40° down (Scout), 38° (Ranger)
Where it points nowrobot.camera_pan(), robot.camera_tilt()degrees
  • The servos turn at about 120° per second, so they need time. Turning from +150° to −150° (300°) takes 2.5 s. Wait for it before you trust the picture: robot.wait(travel / 120 + 0.3).
  • If you ask for more than the limit (say 200°), the servo stops at its limit (150°).
  • To see lines on the floor, keep the default tilt (40° down). To see balls and posts, tilt up to about 10°.
  • ROS 2: publish a std_msgs/Float64 on /camera/pan or /camera/tilt, in radians (0.17 rad = 10°).
camera_pantilt.pytested: every position reached
# Camera pan and tilt test · world: Camera Lab
# Pan:  0 = straight ahead, + = left, - = right, up to 150 degrees each way.
# Tilt: 0 = level, + = down toward the floor (up to 70), - = up (up to 25).
#       The camera starts at 40 degrees down, so it can see lines on the floor.
# The servos turn about 120 degrees per second, so give them a moment.
print("start: pan", round(robot.camera_pan()), "deg, tilt", round(robot.camera_tilt()), "deg down")

for pan in [0, 45, 90, 150, -150, 0]:
    travel = abs(pan - robot.camera_pan())     # how far the servo has to turn
    robot.pan_camera(pan)
    robot.wait(travel / 120 + 0.3)             # 120 degrees per second, plus a little extra
    print("asked pan", pan, "-> now", round(robot.camera_pan()))

for tilt in [70, 0, -25, 40]:
    travel = abs(tilt - robot.camera_tilt())
    robot.tilt_camera(tilt)
    robot.wait(travel / 120 + 0.3)
    print("asked tilt", tilt, "-> now", round(robot.camera_tilt()))

robot.pan_camera(200)                      # too far: the servo stops at its limit
robot.wait(2)
print("asked pan 200 -> now", round(robot.camera_pan()), "(the limit is 150)")
robot.pan_camera(0)

Fingertips that feel dark and light

IR line sensors

Under the front of the robot is a row of small infrared sensors that look straight down. Light floor reflects a lot of light back; black tape reflects almost none. That is all they know, and it is enough to follow a line.

Sensors
5 in a row, 1.8 cm apart (3 to 9, spacing 1 to 3 cm, in the Robot tab)
Values
0 = light floor, 1 = black tape, in between = partly over the tape
Speed
50 readings per second
  • robot.line_sensors() gives the values from left to right.
  • robot.line_position() gives one number: −1 = the line is far to the left, 0 = in the middle, +1 = far to the right, or None when no sensor sees it.
line_simple.pytested on the Line Track
# IR line sensor test · world: Line Track
# Five sensors under the front, left to right. 0 = floor, 1 = black tape.
for _ in range(30):
    values = robot.line_sensors()
    pos = robot.line_position()            # -1 = line far left ... +1 = far right, None = lost
    bar = "".join("#" if v > 0.5 else "." for v in values)
    print(bar, [round(v, 2) for v in values], "position:", None if pos is None else round(pos, 2))
    robot.forward(0.1)
    robot.wait(0.3)
robot.stop()
line_ros2.pytested
# IR line sensor test, ROS 2 style · world: Line Track
import rclpy
from rclpy.node import Node
from std_msgs.msg import Float32MultiArray

class LineTest(Node):
    def __init__(self):
        super().__init__('line_test')
        self.create_subscription(Float32MultiArray, '/line_sensors', self.on_line, 10)

    def on_line(self, msg):
        bar = ''.join('#' if v > 0.5 else '.' for v in msg.data)
        self.get_logger().info(f'{bar}  {[round(v, 2) for v in msg.data]}')

rclpy.init()
rclpy.spin(LineTest())

In real life: a TCRT5000 module or a Pololu QTR sensor array.

The inner ear

IMU (heading and turning)

An IMU (inertial measurement unit) is like the balance sense in your ear. Its gyroscope feels how fast the robot turns; from that, it keeps track of which way the robot faces. It also feels acceleration.

Heading
degrees, −180 to 180 (0 = facing +x, 90 = facing +y)
Turn rate
degrees per second, positive = turning left
Speed
50 readings per second
Noise and drift
gyro noise 0.002 rad/s; heading drift 0 by default (add some in the Robot tab to feel what real IMUs do)
  • robot.heading(), robot.gyro(), and robot.turn(90), which uses the IMU to turn an exact angle.
  • After 180° comes −180°, not 181°. When you compare two headings, wrap the difference: d = (a - b + 180) % 360 - 180.
  • ROS 2: /imu is a sensor_msgs/Imu. Its heading is a quaternion; turn it into an angle with euler_from_quaternion(msg.orientation).
imu_simple.pytested
# IMU test · world: Open Lab
# heading(): degrees, -180..180 (0 = the +x direction, 90 = +y). gyro(): degrees per second.
robot.wait(0.1)                            # let the first reading arrive
print("start heading", round(robot.heading(), 1))
robot.turn_left(1.0)
for _ in range(8):
    robot.wait(0.25)
    print("heading", round(robot.heading(), 1), " turning at", round(robot.gyro(), 1), "deg/s")
robot.stop()
robot.turn(-90)                            # turn exactly 90 degrees right, using the IMU
print("after turn(-90):", round(robot.heading(), 1))
imu_ros2.pytested
# IMU test, ROS 2 style · world: Open Lab
import math
import rclpy
from rclpy.node import Node
from sensor_msgs.msg import Imu
from geometry_msgs.msg import Twist
from tf_transformations import euler_from_quaternion

class ImuTest(Node):
    def __init__(self):
        super().__init__('imu_test')
        self.create_subscription(Imu, '/imu', self.on_imu, 10)
        self.pub = self.create_publisher(Twist, '/cmd_vel', 10)
        self.n = 0

    def on_imu(self, msg):
        roll, pitch, yaw = euler_from_quaternion(msg.orientation)
        self.n += 1
        if self.n % 25 == 0:                # the IMU sends 50 messages a second
            self.get_logger().info(f'yaw {math.degrees(yaw):6.1f} deg   gyro z {msg.angular_velocity.z:+.2f} rad/s')
        t = Twist()
        t.angular.z = 0.8
        self.pub.publish(t)

rclpy.init()
rclpy.spin(ImuTest())

In real life: an MPU-6050 (cheap) or a BNO055/BNO085 (does the heading maths for you).

Counting steps

Wheel encoders and odometry

An encoder counts how far a wheel has turned, in small steps called ticks. If you know how big the wheel is, ticks become meters. Adding up those small moves gives odometry: an estimate of where the robot is, like counting your steps with your eyes closed. It is good over short distances and slowly drifts, because wheels slip.

Ticks per wheel turn
360 (12 to 1440 in the Robot tab)
One tick
0.70 mm (Scout) or 1.31 mm (Ranger): see First steps → One wheel turn
Odometry
x, y in meters and theta in radians, starting from where Run began
  • robot.encoders() gives (left, right) ticks. robot.ticks_per_rev() gives the ticks per turn.
  • robot.odometry() gives (x, y, theta). robot.move(0.5) uses it to drive an exact distance.
  • ROS 2: /wheel_ticks (std_msgs/Int32MultiArray, [left, right]) and /odom (nav_msgs/Odometry). Declare a parameter called wheel_radius and Singularity fills in the robot’s real value.
odom_ros2.pytested
# Wheel odometry, ROS 2 style · world: Open Lab
# /wheel_ticks gives raw ticks; /odom gives the pose worked out from them.
import rclpy
from rclpy.node import Node
from nav_msgs.msg import Odometry
from std_msgs.msg import Int32MultiArray
from geometry_msgs.msg import Twist

class OdomTest(Node):
    def __init__(self):
        super().__init__('odom_test')
        self.radius = self.declare_parameter('wheel_radius', 0.033).value   # filled in from the robot
        self.create_subscription(Int32MultiArray, '/wheel_ticks', self.on_ticks, 10)
        self.create_subscription(Odometry, '/odom', self.on_odom, 10)
        self.pub = self.create_publisher(Twist, '/cmd_vel', 10)
        self.create_timer(1.0, self.report)
        self.ticks, self.xy = None, None

    def on_ticks(self, msg):
        self.ticks = list(msg.data)
        t = Twist()
        t.linear.x, t.angular.z = 0.2, 0.3      # drive a gentle circle
        self.pub.publish(t)

    def on_odom(self, msg):
        p = msg.pose.pose.position
        self.xy = (p.x, p.y)

    def report(self):
        if self.ticks and self.xy:
            self.get_logger().info(f'ticks {self.ticks}  odom x={self.xy[0]:.2f} y={self.xy[1]:.2f}  wheel r={self.radius}')

rclpy.init()
rclpy.spin(OdomTest())

In real life: gear motors with built-in Hall encoders (for example N20 or JGB37-520 motors).

The dot on a phone map

GPS

Singularity’s GPS tells you where the robot is in the world, give or take about 2 cm. Real GPS is much less precise (2 to 5 meters) and does not work indoors, so think of this one as an indoor positioning system.

Gives
(x, y) in meters
Noise
σ = 0.02 m (0 to 0.2 m in the Robot tab)
Speed
10 readings per second
gps_simple.pytested: errors of a few cm
# GPS test · world: Open Lab
# position() = (x, y) in meters with a little noise, like a real GPS (much smaller noise).
robot.wait(0.2)                            # let the first fix arrive
robot.forward(0.2)
for _ in range(10):
    gx, gy = robot.position()
    tx, ty, _ = robot.true_pose()
    print(f"gps ({gx:.2f}, {gy:.2f})   true ({tx:.2f}, {ty:.2f})   error {((gx-tx)**2 + (gy-ty)**2) ** 0.5 * 100:.1f} cm")
    robot.wait(0.5)
robot.stop()
gps_ros2.pytested
# GPS test, ROS 2 style · world: Open Lab
import rclpy
from rclpy.node import Node
from geometry_msgs.msg import PointStamped

class GpsTest(Node):
    def __init__(self):
        super().__init__('gps_test')
        self.create_subscription(PointStamped, '/gps', self.on_gps, 10)

    def on_gps(self, msg):
        self.get_logger().info(f'x={msg.point.x:.2f}  y={msg.point.y:.2f}')

rclpy.init()
rclpy.spin(GpsTest())

In real life: outdoors, a u-blox NEO-M8N (meters) or an RTK GPS (centimeters, expensive). Indoors, UWB beacons such as Marvelmind.

A whisker

Bumper

The bumper only knows one thing: am I touching something right now? It is the last safety net when the other sensors miss something.

Gives
True while any part of the robot’s body touches something, otherwise False
Speed
20 readings per second
bumper_simple.pytested: three bumps, three escapes
# Bumper test · world: Playground
# Drive until something is touched, then back off and turn.
hits = 0
while hits < 3:
    if robot.bumped():
        hits += 1
        print("bump", hits, "at", [round(v, 2) for v in robot.odometry()[:2]])
        robot.backward(0.2)
        robot.wait(0.6)
        robot.turn(120)
    else:
        robot.forward(0.25)
        robot.wait(0.05)
robot.stop()
bumper_ros2.pytested
# Bumper test, ROS 2 style · world: Playground
import rclpy
from rclpy.node import Node
from std_msgs.msg import Bool
from geometry_msgs.msg import Twist

class BumperTest(Node):
    def __init__(self):
        super().__init__('bumper_test')
        self.pub = self.create_publisher(Twist, '/cmd_vel', 10)
        self.create_subscription(Bool, '/bumper', self.on_bumper, 10)
        self.backing = 0

    def on_bumper(self, msg):                  # arrives 20 times a second
        t = Twist()
        if msg.data and self.backing == 0:
            self.get_logger().warn('Bump!')
            self.backing = 15
        if self.backing > 0:
            self.backing -= 1
            t.linear.x, t.angular.z = -0.15, 1.0
        else:
            t.linear.x = 0.25
        self.pub.publish(t)

rclpy.init()
rclpy.spin(BumperTest())

In real life: a micro switch (limit switch) behind a bumper bar, wired to an Arduino pin.

LED and headlights

The robot has a colored LED strip and two headlights. The LED is for you: a status light that shows what the robot is thinking. The headlights are for the camera: they light up the floor and things ahead in a dark room.

CommandWhat it does
robot.led("red")Color by name: red, orange, yellow, green, cyan, blue, purple, pink, white, off
robot.led(255, 120, 0)Color by red, green, blue (0–255, or 0–1)
robot.headlights(0.6)0 = off … 1 = full brightness (True/False work too). Key: H
/ledROS 2: publish std_msgs/ColorRGBA (r, g, b from 0 to 1)
/headlightsROS 2: publish std_msgs/Float32 (0 to 1)
led_status.pytested
# LED and headlights · world: Playground
# One call is enough: the LED keeps its color until you change it,
# you press Run again (Start over) or Reset.
robot.led("blue")                          # by name: red, orange, yellow, green, cyan,
robot.wait(1)                              # blue, purple, pink, white, off
robot.led(255, 120, 0)                     # or by red, green, blue (0-255, or 0-1)
robot.wait(1)

# The most useful LED is a status light that changes with what the robot sees.
robot.headlights(0.6)                      # 0 = off ... 1 = full (key H does the same)
for _ in range(100):
    d = robot.front_distance()
    if d < 0.4:
        robot.led("red")                   # danger: something close
        robot.turn_left(1.0)
    elif d < 0.8:
        robot.led("yellow")                # careful
        robot.forward(0.15)
    else:
        robot.led("green")                 # all clear
        robot.forward(0.3)
    robot.wait(0.1)
robot.stop()
robot.headlights(0)

When a sensor is off

If you switch a sensor off in the Robot tab and your program reads it, the program stops with a friendly SensorOffError that tells you which sensor, and what to use instead. A real robot without that sensor would not have the data either. To check first, use robot.is_on("lidar") (also "camera", "imu", "encoders", "gps", "bumper", "line", "sonar", or one ultrasonic mount like "front").

Stuck on something this page did not answer? Write to us at antiprotontechnologies@gmail.com. Paste what you tried and what happened (the Copy details for support button in Singularity’s Help & Support window helps us a lot).