Skip to content

Instantly share code, notes, and snippets.

@shohei
Last active May 2, 2022 08:22
Show Gist options
  • Save shohei/5430972407822ab89ccbcf75615df1f5 to your computer and use it in GitHub Desktop.
Save shohei/5430972407822ab89ccbcf75615df1f5 to your computer and use it in GitHub Desktop.
modified zbee.py: xbee-arduino-rpi-experiment with DHT11 sensor Raw
#include <DHT.h>
#include <DHT_U.h>
#include <XBee.h>
#include "DHT.h"
#define DHTPIN 2
#define DHTTYPE DHT11
// Initialize XBee ZB client
XBee xbee = XBee();
// Payload byte array
uint8_t payload[8];
// Send to coordinator
XBeeAddress64 addr64 = XBeeAddress64(0, 0);
// Create request for XBee ZB
ZBTxRequest zbTx = ZBTxRequest(addr64, payload, sizeof(payload));
// Initialize DHT sensor module
DHT dht(DHTPIN, DHTTYPE);
void set_float_to_payload(float value, int index) {
uint8_t *value_array;
value_array = reinterpret_cast<uint8_t*>(&value);
for(int i=0; i<sizeof(value); i++){
payload[i+index] = value_array[i];
}
}
void setup() {
Serial.begin(9600);
xbee.setSerial(Serial);
dht.begin();
}
void loop() {
delay(3000);
float temperature = dht.readTemperature();
float humidity = dht.readHumidity();
set_float_to_payload(temperature, 0);
set_float_to_payload(humidity, 4);
xbee.send(zbTx);
}
#!/usr/bin/python
"""
Application to receive data from XBee ZB using XBee Python Library.
"""
from xbee import ZigBee
import serial
import struct
import codecs
# TODO Replace with the serial port where your receiver module is connected.
PORT = '/dev/ttyUSB0'
# TODO Replace with the baud rate of you receiver module.
BAUD_RATE = 9600
# Open serial port
myDevice = serial.Serial(PORT, BAUD_RATE)
# Create API object
xbee = ZigBee(myDevice)
def prettyHexString(str):
"split string by 2 length"
return ' '.join([str[i:i+2] for i in range(0, len(str), 2)])
# Continuously read and print packets
print(">> Waiting for data...")
while True:
try:
response = xbee.wait_read_frame()
source_addr = codecs.encode(response['source_addr_long'],'hex').upper()
payload = prettyHexString(codecs.encode(response['rf_data'],'hex').upper())
data = struct.unpack('ff', response['rf_data'])
print('From %s >> [%s] | { temperature: %.1f degrees, humidity: %.1f%% }' % (source_addr, payload, data[0], data[1]))
except KeyboardInterrupt:
break
myDevice.close()
@jsonale
Copy link

jsonale commented May 2, 2022

I have used code you provided, but the message sent is wrong. When I upload zbee.ino, Serial monitor displays some strange characters. So, data sent to raspberry is wrong. Can you help me solve this problem?
Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment