我正在开发一个无线传感器网络,其中我有一个协调器路由器(API模式2)连接到Raspberry Pi 2,5或更多路由器的API模式2。每个路由器都连接到Arduino Uno。 Unos还有不同的传感器(温度,湿度等)。我必须将数据从传感器发送到协调器并进行处理。我使用一个路由器和协调器(只有两个XBee S2模块)成功传输了数据。在Arduini上我正在使用Andrew的库https://github.com/andrewrapp/xbee-arduino而在Pi上我正在使用Python-xbee库https://github.com/nioinnovation/python-xbee。对于单个路由器和协调器,我的代码是: Arduino代码(路由器):
#include <XBee.h>
#include <math.h>
// create the XBee object
XBee xbee = XBee();
int sensor = A5;
uint8_t payload[8] = {0, 0, 0, 0, 0, 0, 0, 0};
// union to convert float to byte string
union u_tag {
uint8_t b[4];
float fval;
} u;
// SH + SL Address of receiving XBee
XBeeAddress64 addr64 = XBeeAddress64(0x0013a200, 0x40DC7C90);
ZBTxRequest zbTx = ZBTxRequest(addr64, payload, sizeof(payload));
ZBTxStatusResponse txStatus = ZBTxStatusResponse();
int statusLed = 13;
int errorLed = 12;
void flashLed(int pin, int times, int wait) {
for (int i = 0; i < times; i++) {
digitalWrite(pin, HIGH);
delay(wait);
digitalWrite(pin, LOW);
if (i + 1 < times) {
delay(wait);
}
}
}
double Thermistor(int RawADC)
{
double Temp;
Temp = log(10000.0 * ((1024.0 / RawADC - 1)));
Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp )) * Temp );
Temp = Temp - 273.15; // Convert Kelvin to Celcius
//Temp = (Temp * 9.0)/ 5.0 + 32.0; // Convert Celcius to Fahrenheit
return Temp;
}
void setup() {
pinMode(statusLed, OUTPUT);
pinMode(errorLed, OUTPUT);
Serial.begin(9600);
}
void loop() {
float rawADC = analogRead(sensor);
float t = Thermistor (rawADC);
// check if returns are valid, if they are NaN (not a number) then something went wrong!
if (!isnan(t)) {
// convert temperature into a byte array and copy it into the payload array
u.fval = t;
for (int i=0;i<4;i++){
payload[i]=u.b[i];
}
u.fval = 100.33;
for (int i=0;i<4;i++){
payload[i+4]=u.b[i];
}
xbee.send(zbTx);
flashLed(statusLed, 1, 100); // flash TX indicator
// after sending a tx request, we expect a status response, wait up to half second for the status response
if (xbee.readPacket(500)) {
// got a response!
// should be a znet tx status
if (xbee.getResponse().getApiId() == ZB_TX_STATUS_RESPONSE) {
xbee.getResponse().getZBTxStatusResponse(txStatus);
// get the delivery status, the fifth byte
if (txStatus.getDeliveryStatus() == SUCCESS) {
// success. time to celebrate
flashLed(statusLed, 5, 50);
} else {
// the remote XBee did not receive our packet. is it powered on?
flashLed(errorLed, 3, 500);
}
}
} else if (xbee.getResponse().isError()) {
//nss.print("Error reading packet. Error code: ");
//nss.println(xbee.getResponse().getErrorCode());
} else {
// local XBee did not provide a timely TX Status Response -- should not happen
flashLed(errorLed, 1, 50);
}
}
delay(2000);
}
Raspberry Pi Code(协调员):
from xbee import ZigBee
import serial
import struct
import datetime
PORT = '/dev/ttyUSB0'
BAUD_RATE = 9600
def hex(bindata):
return ''.join('%02x' % ord(byte) for byte in bindata)
# Open serial port
ser = serial.Serial(PORT, BAUD_RATE)
# Create API object
xbee = ZigBee(ser,escaped=True)
# Continuously read and print packets
while True:
try:
response = xbee.wait_read_frame()
sa = hex(response['source_addr_long'])
rf = hex(response['rf_data'])
obj = createObject(response)
obj.createPacket()
print ("Temperature: %.2f" % obj.packet['temperature'],
"Humidity: %.2f" % obj.packet['humidity'],
"Source Address: 0x%s" % obj.packet['sourceAddressShort'],
"Timestamp: %s" % obj.packet['timestamp'].isoformat())
except KeyboardInterrupt:
break
ser.close()
class createObject:
def __init__(self, response):
self.sourceAddrLong = hex(response['source_addr_long'])
self.rfData = hex(response['rf_data'])
self.sourceAddrShort = hex(response['source_addr_long'][4:])
self.options = response.pop('options')
self.frameType = response['id']
self.temperature = struct.unpack('f',response['rf_data'][0:4])[0]
self.humidity = struct.unpack('f',response['rf_data'][4:])[0]
self.dataLength = len(response['rf_data'])
self.packet={}
self.dateNow = datetime.datetime.utcnow()
self.packetJson=0
def createPacket(self):
self.packet.update({
'timestamp' : self.dateNow,
'temperature' : self.temperature,
'humidity' : self.humidity,
'dataLength' : self.dataLength,
'sourceAddressLong' : self.sourceAddrLong,
'sourceAddressShort' : self.sourceAddrShort,
'options' : self.options,
'frameType' : self.frameType
})
我有一些我无法找到答案的问题。我几乎到处都看,但仍有一些混乱。
在Arduino代码中,最后有一部分代码检查状态响应(我没有编写代码,在互联网上找到它)。当我进行设置时,连接到引脚12的errorLED闪烁一次并查看代码,这意味着“本地XBee未提供及时的TX状态响应”。我的问题是,我是否必须自己从python中的协调器发送响应,还是自动生成?如果我必须自己做,我该怎么做?因为现在没有回应。我的设置正常,因为我在我的Pi上获得了正确的值。
当我有多个路由器时,如何在代码中处理它?我会继续每隔2秒从arduino发送传感器值并循环通过Pi上的地址,还是通过另一种方式完成它?我很困惑。
现在,如果我添加更多路由器,它们将继续发送带有传感器值的帧,协调器将循环读取它们。如何设置系统,使协调器向每个路由器发送信号并询问数据,然后路由器回复数据?有可能吗?
答案 0 :(得分:0)
当本地XBee已确认传送到远程XBee时,会自动发送传送状态帧。这是一个低级别的确认。我的猜测是代码的逻辑存在问题。也许响应在500ms后回复。唯一的方法是重新构建代码以不断轮询本地XBee的帧,每两秒发送一次传感器状态帧,并跟踪自上次成功传输状态帧进入以来它已经存在多长时间我也建议在这里增加波特率,特别是因为现有的Arduino代码不经常处理字节(例如,2秒的空闲而不读取串口)。
看起来Raspberry Pi代码已经设置为处理来自&#34;连续读取和打印数据包中的多个设备的数据&#34;环。我建议将XBee模块配置为115200bps并使用新值更新Python代码,这样您就不会限制数据速率。
您当前的设计更易于管理 - 网络上的路由器将始终报告其传感器读数。我想你甚至可以更新代码使用00000000-00000000作为目标地址,路由器将始终发送给协调器。但您可以修改Raspberry Pi代码以保留路由器MAC地址列表(通过ATND
节点发现发现),并根据需要向它们发送请求。您需要修改Arduino代码以监视入站帧,并在请求进入时生成出站帧。
我建议在您的设置中添加第二个路由器而不进行任何代码更改,然后只是看看它是如何工作的。据我所知,Raspberry Pi只会打印具有不同源地址的数据包。