I want help reading serial data from XBee using Python

Hey everyone! :waving_hand:

I am working on a small project where I am trying to read data from an XBee module using Python. I have got the hardware all set – XBee connected via USB & it shows up fine on my machine. I am using the digi-xbee Python library (v1.4.1 I think?) & Python 3.11.

I can send AT commands just fine but when I try to read serial data , I either get nothing or weird characters. I have double-checked the baud rate & all the usual settings but still no luck.

I even tried following a Python tutorial that covered serial communication basics but still could not get the output right. Could it be something with the way the data is being parsed or maybe a buffer issue?

Thank you.:slight_smile:

Which XBee module are you running and how is it configured?

What IDE are you working with?

It’s generally the XBee mode against how you’re reading the data, not Python being strange.

First and foremost, you should avoid reading raw serial, such as pyserial, while using the digi-xbee library when the module is in API mode.readline(). Since API frames are binary rather than line-based, treating them as text would undoubtedly result in “weird characters.” That’s to be anticipated. Let the library decode the frames for you by using the add_data_received_callback() or read_data() methods.

In the event that the XBee is operating in transparent (AT) mode:

Verify that the baud and parity/stop bits are agreed upon by both parties.

Many XBee payloads are simply raw bytes, so don’t assume they include newline-terminated data.

read bytes rather than strings, and only decode after you are familiar with the format.

It is also worthwhile to verify:

(0 = transparent, 1/2 = API) is the AP parameter. 90% of these problems are caused by mixing this up.

If you don’t parse frames, escaping (API mode 2) may seem particularly jumbled.

To avoid decoding outdated information, use buffering by using flushInput() before reading.

Printing repr(data) rather than decoding to utf-8 is a simple sanity check in Python. It’s binary payloads, not text, if it all of a sudden “makes sense.”

In summary, the ability to execute AT commands does not imply that your data route is text-friendly. If you’re in API mode, match your read method to the XBee mode and let the digi-xbee library handle frames.

thanq for this information