Interfacing Raspberry Pi with DHT11 | Sending DHT11 data to client

Interfacing Raspberry Pi with DHT11 | Sending DHT11 data to client

 

In the above image, we see DHT11 sensor interfaced with Raspberry Pi 3. GPIO2 from the GPIO Header of Raspberry Pi is connected to the Signal pin of DHT11. 3V3 and GND pins from Raspberry Pi header are used to power the DHT11 sensor. In this project, we are configuring Raspberry Pi as server and laptop as client and upon client request, Temperature and humidity sensor are sent from Raspberry Pi.

The explanation for the same is in the below link:

Raspberry Pi Server side code is as below:

import socket
import time
import Adafruit_DHT
sensor = Adafruit_DHT.DHT11
pin = 2
bufferSize = 1024
msgFromServer = "This is RPi Server"
ServerPort = 2222
ServerIP = '192.168.0.164'
bytesToSend = msgFromServer.encode('utf-8')
RPIsocket=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
RPIsocket.bind((ServerIP,ServerPort))
print('Server is Up and Listening..')
while True:
    message,address = RPIsocket.recvfrom(bufferSize)
    message = message.decode('utf-8')
    print(message)
    print('Client Address',address[0])
    humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
    if message == 'DHT11-Humidity':        
        if humidity is not None:
            msg = str(humidity)
            msg = msg.encode('utf-8')
            RPIsocket.sendto(msg,address)
        else:
            print('Failed to get reading. Try again!')
    elif message == 'DHT11-Temperature':        
        if temperature is not None:
            msg = str(temperature)
            msg = msg.encode('utf-8')
            RPIsocket.sendto(msg,address)
        else:
            print('Failed to get reading. Try again!')


Laptop configured as Client and below is the code for the same:

import socket
msgFromclient = 'This message is from PC, I am client'
bytesToSend = msgFromclient.encode('utf-8')
serverAddress = ('192.168.0.164',2222)
bufferSize = 1024
UDPClient = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
while True:
    data = 'DHT11-Humidity'
    data = data.encode('utf-8')
    UDPClient.sendto(data,serverAddress)
    data,address = UDPClient.recvfrom(bufferSize)
    data = data.decode('utf-8')
    print('Humidity', data)
    print('Server IP Address: ',address[0])
    print('Server Port: ',address[1])

    data = 'DHT11-Temperature'
    data = data.encode('utf-8')
    UDPClient.sendto(data,serverAddress)
    data,address = UDPClient.recvfrom(bufferSize)
    data = data.decode('utf-8')
    print('Temperature', data)
    print('Server IP Address: ',address[0])
    print('Server Port: ',address[1])

Post a Comment

0 Comments