About The Ultrasonic Sensor

RaspbotV2 comes equiped with an ultrasonic sensor at the front of the car. An ultrasonic sensor is typically used to measure the distance of an object in front of the car by sending a ultrasonic wave, and measuring the time until it returns.

\[ v = \frac{d}{t} \implies \boxed{d = vt} \]

The shield of the robot already does the calculation for us and stores the distance value in the register according to its datasheet.

the relevant data:

Type Of Data Register Type Information Other
Ultrasonic Control Switch 0x07 Write buf[0]: turn off/on 0/1 When you don't use the ultrasonic wave, remember to turn it off. Don't turnon this button when the ultrasonic wave is not plugged in, otherwise it won't work properly.
Ultrasonic data (low bit) 0x1A Read 0x00-0xFF Default value: 0x00, Unit: mm
Ultrasonic data (high bit) 0x1B Read 0x00-0xFF

Using The Ultrasonic Sensor

Since the library doesn't directly have built-in methods to read and compute the distance for us, we'll do it manually by reading and writing to the shield via I2C communication.

Writing And Reading From Registers

The Raspbot_Lib library has built in functions to read and write to the shield attached to the Raspberry PI via I2C communication.

To write to an address:

reg = 0x07
data = [1]
bot.write_array(reg, data)

To read from an address:

reg = 0x0D
desired_block_length = 1
output = bot.read_data_array(reg, desired_block_length)
# output is a list of bytes

Turning On/Off The Ultrasonic Sensor

To turn on the ultrasonic sensor:

Use prebuilt function:

bot.Ctrl_Ulatist_Switch(1)

Or directly write to the register:

reg = 0x07
data = [1]
bot.write_array(reg, data)

Note: Generally, it's best to turn of the sensor when it's not in use. When writing a try-catch block, it's important to turn off the ultrasonic sensor when something goes wrong.

Reading The Distance Value

The total distance of 2 bytes is split into 2 registers, 0x1A and 0x1B for low and high bits respectively. Its units is in millimeters \((\text{mm})\).

First, we retrive the 2 bytes from the register.

low_bit_reg = 0x1A
high_bit_reg = 0x1B
desired_block_length = 1
low_bit_distance = bot.read_data_array(low_bit_reg, desired_block_length)[0]
high_bit_distance = bot.read_data_array(high_bit_reg, desired_block_length)[0]

If for instance, low_bit_distance=0xE8 and high_bit_distance=0x03, the whole distance would be 0x03E8.

\[ \texttt{0x}\underbrace{\texttt{03}}_{\text{high bit |}}\underbrace{\texttt{E8}}_\text{ low bit } \]

To do this we can: 1. 0x03 << 8 to get 0x0300 2. Then simply take 0x0300 + 0x00E8 or 0x0300 | 0x00E8 to get 0X03E8

Programically, to combine these two values, we: 1. Shift high_bit_distance 1 byte (8 bits) to the left 2. Either take high_bit_distance + low_bit_distance or high_bit_distance|low_bit_distance to get the real distance

distance = (high_bit_distance << 8)|low_bit_distance