LED Sync
This behavior takes inspiration from classic synchronization behavior in nature such as the synchronization of fireflies. It starts off with robots flashing at random intervals, using neighbor communication each robot transmits its offset from the next flash interval and calculates the next common interval using the intervals from other neighbors. This will result in a synchronized flash for all robots.
The function init()
initializes the values to all the robots before execution. As shown, iteration
refers to the number of time steps where 1 time step = 1 milisecond.
The flash period is set to 3 seconds and the length of each flash is 3 miliseconds. The random seed is the ID of the robot to ensure random numbers for each robot.
The timestep for the next flash is a random number generated using rng.uniform()
. receiveOffset()
allows the robots to listen to the offset sent by its
neighbors.
# Executed at init time function init() { iteration = 0 FLASH_PERIOD = 30 FLASH_LENGTH = 3 rng.setseed(id) next_flash = rng.uniform(1,200) % 30 # random number generator goes here instead of ID receiveOffset() }
receiveOffset()
Calculation of the next flash is done once the offset is received from other neighbors. sum
is the sum of the current number of timesteps and the offset
sent by the neighbors. It is an indication of how close or far the next flash of the robot compares to its neighbors. The next flash is either incremented or decremented
when its is less than or greater than sum
.
# Calculates the next flash time based on the offset received function receiveOffset() { neighbors.listen("offset", function(vid, value, rid){ t = iteration + value c = next_flash + FLASH_PERIOD/2 d = t + FLASH_PERIOD/2 if((next_flash < t) and c > t) { next_flash = next_flash + 1 } else if((next_flash > t) and (next_flash < d)) { next_flash = next_flash - 1 } }) }
upper_bound
and upper_bound_sum
are the upper limits of the interval range. It is to scale down the intervals to provide accurate calculations.
upper_bound_sum
exists as when next_flash
is greater than sum
it may be greater than upper_bound
too.
sendOffset()
This function calculates the offset of the robot and sends it to its neighbors. The offset is calculated by the difference in the current time step and the next flash timestep. If the current timestep is greater than the next flash, the offset is 0.
# Send own offset to neighbors function sendOffset() { if(next_flash >= iteration) { offset = next_flash - iteration } else { offset = 0 } neighbors.broadcast("offset", offset) }