UltrasonicRead function will not allow return or global variable


I am using the ultimate 2.0 to make a rumba like bot. the problem Im running into is with the onRead function that is called by the ultrasonicRead function. the function will not allow return variables or global variables to use the distance in the rest of the code.

here is a simple test code to use global variables :
from megapi import *
import time
x = 0
dist = 0

def onRead(v):
global dist
dist = v

def square(num):
global x
x = 3
return num*num

if name== “main”:

sqr = square(3)


and here is the result :

Version:3.7.3 (default, Dec 20 2019, 18:57:59)
[GCC 8.3.0]
init Megapi
<megapi_python3.mSerial object at 0xb5ec7e30>

distance 47.01724231640625cm

as you can see my test function works but not the ultrasonic one. Anyone know the reason for this or a way to work around it?


OK I don’t have a ultimate 2.0 but have done a lot of coding of all sorts of robots.

bot.ultrasonicSensorRead() function should return a value and I assume you normally only pass 1 parameter to it (the port)

I assume something this will do what you want.

dist = bot.ultrasonicSensorRead(7)


OotB: Looks like the bot.ultrasonicSensorRead takes two parameters, the second is the callback function
as per: https://github.com/Makeblock-official/PythonForMegaPi/blob/master/examples/ultrasonicSensorRead.py

stuartwatts: It looks like the call to print ‘dist’ is being executed before the onRead function (which sets the global dist variable), which is why it’s zero rather than 47.02.

Your concept of global variables is correct, just that the timing is off.

Take a look at the code from dr-roboto here Raspberry pi + python ultra sonic sensor - there’s a sleep function in his while loop, that may be designed to allow the read to happen before the rest of the code executes. I’m afraid I’m neither a Python coder nor an ultimate owner, but that’s where I’d start looking. See if his function works then go from there.


I use the sleep as a settle time on the ultrasonic. I have used the raspberry PI and python to control mbots, starter and ultimate robots.


This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.