前言

用python编程来控制串口(COM口),来让一对XBee进行通讯。不需要借助终端来发送和接收数据,增大了XBee使用的灵活性。这才是使用XBee模块的最初目的。使用XBee的API模式来通讯非常容易(在没做出来之前很头大),我们仅需要添加相关的库,然后开始用就完事了。我们甚至不需要深刻的理解XBee API协议,有兴趣也可以去看一下。
关键词:python、XBee、串口、API

什么是API?

API是application programming interface的简写,它们就是一个程序跟另一个程序进行交互的标准接口。简单地说,它们就是两段程序代码之间的桥梁(个人理解)。我们在使用终端来进行通讯时,XBee处于transparent/command模式。这种情况下,初学者很容易上手,配置完成就能传递和接收数据,并且可以直接在屏幕上阅读。这是XBee平台的一个大优势,但是它们对于计算机的鲁棒性、显性性和效率就不太好。计算机喜欢处理数字,喜欢用明确且高度结构化的方式传输。API可以提供能用来编程的接口,API模式使无线电能够根据人和人的需求平等地服务于人和计算机。

代码

其中一个XBee作为接收方,另一个作为发送方。

接受方的代码(receiver)

#! /usr/bin/python
from digi.xbee.devices import XBeeDevice
from xbee import XBee, ZigBee
import serial

# TODO: Replace with the serial port where your local module is connected to.
PORT = "COM3"
# TODO: Replace with the baud rate of your local module.
BAUD_RATE = 9600


def main():
    print(" +-----------------------------------------+")
    print(" | XBee Python Library Receive Data Sample |")
    print(" +-----------------------------------------+\n")

    device = XBeeDevice(PORT, BAUD_RATE)


    try:
        device.open()

        def data_receive_callback(xbee_message):
            print("From %s >> %s" % (xbee_message.remote_device.get_64bit_addr(),
                                     xbee_message.data.decode()))

        device.add_data_received_callback(data_receive_callback)

        print("Waiting for data...\n")
        input()

    finally:
        if device is not None and device.is_open():
            device.close()


if __name__ == '__main__':
    main()

发送方代码(transfer)

from digi.xbee.devices import XBeeDevice

# TODO: Replace with the serial port where your local module is connected to.
PORT = "COM5"
# TODO: Replace with the baud rate of your local module.
BAUD_RATE = 9600

DATA_TO_SEND = "fuck liunaifeng!"
REMOTE_NODE_ID = "XBEE_B"


def main():
    print(" +--------------------------------------+")
    print(" | XBee Python Library Send Data Sample |")
    print(" +--------------------------------------+\n")

    device = XBeeDevice(PORT, BAUD_RATE)

    try:
        device.open()
        print(1111)

        # Obtain the remote XBee device from the XBee network.
        xbee_network = device.get_network()
        remote_device = xbee_network.discover_device(REMOTE_NODE_ID)
        if remote_device is None:
            print("Could not find the remote device")
            exit(1)

        print("Sending data to %s >> %s..." % (remote_device.get_64bit_addr(), DATA_TO_SEND))

        device.send_data(remote_device, DATA_TO_SEND)

        print("Success")

    finally:
        if device is not None and device.is_open():
            device.close()


if __name__ == '__main__':
    main()

配置
在使用API的时候需要将XBee模块配置成API模式,操作非常简单,如下图所示。
在这里插入图片描述
选择API enabled[1]之后,点后面的笔的图标,把它写进去。

REMOTE_NODE_ID就是NI里面的参数,如下图
在这里插入图片描述

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐