mBot: Ultrasonic Sensor + mBlock IDE


#1

Hello there.

I used Scratch before a bit, but am new to the mBot. I want to control the robot with the keys on my computer keyboard. It works already pretty good, if an arrow is pressed, it will go in said direction, if I release the button it will stop.

[when up arrow key pressed] - run forward at speed 100
[when up arrow key released] - run forward at speed 0

Now I want to include the Ultrasonic Sensor, so I tried to implement an “if - else”.
It works, but not properly: if the robot is too close to an obstacle when I press the up arrow it will rotate to the right and then go forward. But if it is already running and an obstacle comes closer, it just keeps on running…

I am not sure if it is my fault or if the 2.4G connection is just too slow?

Attached is my code:
22

Thank you :slight_smile:


#2

Hi Jeannie,

you could try adding a forever block to the piece of code with the ultrasonic sensor. I think that could help.

Greetings,

PinkyPepper


#3

I am not sure if it’s the slow connection or if it’s a problem with the code, but if I just use my code above and change the “when up arrow key pressed” to “when flag clicked” it works… So the little mBot will drive around automatically from now on, but at least he won’t run into things anymore :wink: