Im trying to make a small 3 connected robots. They have to send and receive sensor data from each other and take an action to make the reads tends to zero again . Iam trying to exchange the angle of the movements to let the other one follow him . Iam using the MQTT and it works very well . But when i try to get the data from def on_message to use it in the next while the variable isn't global . the code as follow :
############### MQTT section ##################
# when connecting to mqtt do this;
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe(sub_topic)
# when receiving a mqtt message do this;
def on_message(client, userdata, msg):
masterangel = int(msg.payload)
print ( masterangel )
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(Broker, 1883, 60)
client.loop_start()
# Start the Program
psm.screen.termPrintAt(1, "Press Go to stop program")
while(not doExit):
oldAngel = Angel
Angel = gyro.readValue()
Angelshow = "Current Angel ="+" "+str (Angel)
if ( oldAngel != Angel):
psm.screen.termPrintAt(5, Angelshow)
if (Angel < masterangel) :
psm.BBM1.setSpeedSync(20)
psm.BAM1.floatSync()
elif (masterangel < Angel ) :
psm.BAM1.setSpeedSync(20)
psm.BBM1.floatSync()
client.publish(pub_topic, "test")
now has anyone an Idea how can i use the variable "masterangel" in the while loop ? by the way the print order of works fine .
print ( masterangel )
thank you in Advance and i appreciate your Help
You need to initialise the variable outside the scope of the onMessage
function and then mark it as a global variable in the onMessage
functions.
Take a look at the python global
keyword.
############### MQTT section ##################
# when connecting to mqtt do this;
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe(sub_topic)
# when receiving a mqtt message do this;
def on_message(client, userdata, msg):
# use global version not local
global masterangel
masterangel = int(msg.payload)
print ( masterangel )
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(Broker, 1883, 60)
client.loop_start()
# initialise variable to starting value
masterangel = 0
# Start the Program
psm.screen.termPrintAt(1, "Press Go to stop program")
while(not doExit):
oldAngel = Angel
Angel = gyro.readValue()
Angelshow = "Current Angel ="+" "+str (Angel)
if ( oldAngel != Angel):
psm.screen.termPrintAt(5, Angelshow)
if (Angel < masterangel) :
psm.BBM1.setSpeedSync(20)
psm.BAM1.floatSync()
elif (masterangel < Angel ) :
psm.BAM1.setSpeedSync(20)
psm.BBM1.floatSync()
client.publish(pub_topic, "test")
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments