1.2.53. fejezet, RF 433MHz adatátvitel

Antennának egy 173mm hosszú vezetéket érdemes csatlakoztatni az adó-vevő párra.

Adó kód

#include <VirtualWire.h>
#include "DHT.h"
#include "LowPower.h"
 
#define DHTPIN 5
 
#define DHTTYPE DHT22 
 
const int led_pin = 13;
const int transmit_pin = 10;
 
struct package
{
  float temperature ;
  float humidity ;
};
 
typedef struct package Package;
Package data;
 
DHT dht(DHTPIN, DHTTYPE);
 
void setup()
{
    // Initialise the IO and ISR
    vw_set_tx_pin(transmit_pin);
    vw_set_ptt_inverted(true); // Required for DR3100
    vw_setup(4096);       // Bits per sec
    pinMode(led_pin, OUTPUT);
}
 
void loop()
{
  digitalWrite(led_pin, HIGH); // Flash a light to show transmitting
  readSensor();
  vw_send((uint8_t *)&data, sizeof(data));
  vw_wait_tx(); // Wait until the whole message is gone
  digitalWrite(led_pin, LOW);
  LowPower.idle(SLEEP_8S, ADC_OFF, TIMER2_OFF, TIMER1_OFF, TIMER0_OFF, 
                SPI_OFF, USART0_OFF, TWI_OFF);
}
 
void readSensor()
{
 dht.begin();
 delay(1000);
 data.humidity = dht.readHumidity();
 data.temperature = dht.readTemperature();
}

Vevő kód

#include <VirtualWire.h>
 
const int receive_pin = 2;
 
struct package
{
  float temperature = 0.0;
  float humidity = 0.0;
};
 
typedef struct package Package;
Package data;
 
void setup()
{
    Serial.begin(9600);
    vw_set_rx_pin(receive_pin);
    vw_setup(4096);   // Bits per sec
    vw_set_ptt_inverted(true); // Required for DR3100
    vw_rx_start();       // Start the receiver PLL running
}
 
void loop()
{
    uint8_t buf[sizeof(data)];
    uint8_t buflen = sizeof(data);
 
  if (vw_have_message())  // Is there a packet for us? 
  {
    vw_get_message(buf, &buflen);
    memcpy(&data,&buf,buflen);
    Serial.print("{\"temperature\":\"");
    Serial.print(data.temperature);
    Serial.print("\",\"humidity\":\"");
    Serial.print(data.humidity);
    Serial.println("\"}");
  }
}

Soros portról érkező adatok feldolgozás Python-al

Szükséges telepíteni a pySerial könyvtárat

pip install pyserial

A fogadott adatokat JSON objektummá alakítja és kiírja STDOUT-ra a következő kód:

import serial
import json
from types import SimpleNamespace
 
ser = serial.Serial(
    port='COM3',\
    baudrate=9600,\
    parity=serial.PARITY_NONE,\
    stopbits=serial.STOPBITS_ONE,\
    bytesize=serial.EIGHTBITS,\
        timeout=1)
 
print("connected to: " + ser.portstr)
ser.isOpen()
 
while True:
	bs = ser.readline()
	if bs != b'':
		line = bs.decode("utf-8")
		obj = json.loads(line, object_hook=lambda d: SimpleNamespace(**d))
		print("temperature:" + obj.temperature)
		print("humidity:" + obj.humidity)
ser.close()

Kapcsolódó hivatkozások