How it works

All XBee applications should import the xbee DigiMesh library for Python. We can set the serial port for each XBee module. You can change this serial port to one of your liking.

import time 
from xbee import DigiMesh 
import serial 
 
#PORT = 'COM7' 
PORT = '/dev/cu.usbserial-A9CNVHXX' 
BAUD_RATE = 9600 
 
# Open serial port 
ser = serial.Serial(PORT, BAUD_RATE) 
 
# Create API object 
xbee = DigiMesh(ser, escaped=True) 
import pprint 
pprint.pprint(xbee.api_commands) 

In the XBee reader application, we listen for incoming messages from XBee by calling the wait_read_frame() function. After a message is received, we decode the data by calling the decodeReceivedFrame() function.

while True: 
    try: 
        data = xbee.wait_read_frame()         
        decodedData = decodeReceivedFrame(data) 
        print(decodedData) 
 
    except KeyboardInterrupt: 
        break 

To decode the packet frame, we parse the JSON data using the decodeReceiveFrame() function. We declare the following functions:

def ByteToHex(byteStr): 
    return ''.join(["%02X" % ord(x) for x in byteStr]).strip() 
 
 
def decodeReceivedFrame(data): 
    source_addr = ByteToHex(data['source_addr']) 
    rf_data = data['data'] 
    options = ByteToHex(data['options']) 
    return [source_addr, rf_data, options] 

Then, we send data on the XBee sender application. We set the receiver address to FF. That's a broadcast address so all XBees will receive messages on the same mesh network. To send data, we call the tx() function.

# xbee with long address 
XBEE2_ADDR_LONG = "x00x00x00x00x00x00xFFxFF" 
 
while True: 
    try: 
        print "send data" 
        xbee.tx(frame='0x1', dest_addr=XBEE2_ADDR_LONG, data='Hello XBee 2') 
        time.sleep(1) 
    except KeyboardInterrupt: 
        break 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.124.232