Have you seen our new promotions? 15% flat discount on over 180 products!! Click here to see the items!

Wireless Communication In Raspberry Pi

Posted by Momen Odeh 27/03/2017 0 Comment(s)

Welcome to Zeroohm Raspberry Pi Training series. In this series of Raspberry Pi Training, Zeroohm will focus its efforts on helping the community learn more about Raspberry Pi fundamentals and basics starting with basic control of LED's, motors, sensors and utilizing of wirless communication. We hope that you find this useful, Please, leave a comment for any questions or comments or reviews!

We provide all our trainings for groups from schools, universities, public sector and private sector in Abu Dhabi, Dubai, Sharjah, Fujirah, RAK or anywhere in UAE. Please,click here to contact us directly for any training inquires.

Our Raspberry Pi training series:

1. Introduction to Raspberry Pi

2. Analog Inputs/Output In Raspberry Pi

3. Wireless Communication in Raspberry Pi

 

Experiment 1: Email.

Emails is known as a fast and efficient form of communication. With raspberry pi, some projects or applications might require you to send and automatic email to someone, like an alarm for some incidents or event reminders.

In this task you will send an email using python and Simple Mail Transfer Protocol (SMTP) with the help of some libraries.

1. Connect the following Circuit using the shown components.

2. From raspberry pi start menu go to ‘Programming’ then open ‘Python 3 (IDLE)’.

3. Write the following code:

import time  
from gpiozero import MCP3008
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

GPIO.setmode(GPIO.BOARD)

Temperature = MCP3008(0) #define the MCP30088 channel

count = 0

while True:
    volt = Temperature.value*3.3
    TempC = (volt - 0.5) * 100
    TempF = (TempC * (9.0/5.0)) +32.0
    print('The Temperature in celsius is = ' + str(TempC))
    if TempC > 28:
    count = 0
    if count == 0:
                  msg = MIMEMultipart()
           msg['From'] = FromEmail
           msg['To'] = ToEmail
           msg['Subject'] = EmailSubject

           body = EmailBody
           msg.attach(MIMEText(body, 'plain'))

           server = smtplib.SMTP('smtp.gmail.com', 587)
           server.starttls()
           server.login(FromEmail, FromPassword)
           EmailData = msg.as_string()
           
           server.sendmail(FromEmail, ToEmail, EmailData)
                  server.quit()
           
                  count = 1
           
    elif TempC < 27:
        count = 0

    time.sleep(1)

4. Run the code by pressing “F5”.

Discussion:

  • We first import MCP3008 library to the code so that we can read the analog value easily.
  • Also we import the ‘smtp’ library, this library will make your life easier because it runs the Simple Mail Transfer Protocol (SMTP) for you. A Protocol in a set of rules the guides a process between two or more entities (computer, people …etc.), in this case a protocol will guide the transfer of email data between two servers. If you don’t use the library you’ll have to write down the protocol algorithm yourself, and this will take FOREVER!!
  • The next step is to start an infinite ‘While’ loop to read the temperature continuously.
  • After we read the value of the sensor we compare it to the setting Temperature.
  • Then we start an email object with the command ‘objectName = MIMEMultipart()’.
  • Then we set the source, destination, subject and content (body) of the email.
  • Then we attach the parts together to make the email, to explain the library ‘MIMIMultipart’ lets you write the email in multiple part (i.e source, destination, subject and content) then it companies those parts to for the email.
  • The next step is accessing the email service of the source email address using the SMTP protocol. To do so we create service object ‘objectName = smtplib.SMTP(host,port)’, for smtp service the port number is 587.
  • Then we start the service and login to the email. The command ‘msg.as_string()’ return the entire message flattened as a string which is necessary format to send the email, to understand more try ‘print(EmailDate)’ after the command.
  • Last we should close the service to terminate the connection.
  • Note: the variable count equals zero at first and after we send the email we make it one, this is an easy technique to insure that we send the email once and not at each loop.

 

Experiment 2: Xbee transmission with raspberry pi.

XBee is a short range low data rate wireless communication system that works on the concept of mesh networking. It is cost and enables low power/low bandwidth simple wireless communication between two or more xbee nodes.

In this experiment you’ll be reading the temperature humidity in the raspberry pi and then sending the date and displaying it on your laptop:

1. Connect the following Circuit using the shown components.

2. If not installed before, install the libraries that will make our life easy!

  • Adafruit DHT11 library:
  1. Copy the repository from adafruit by running this command in terminal:

Git clone https://github.com/adafruit/Adafruit_Python_DHT.git

  1. Open the directory:

cd Adafruit_Python_DHT

  1. Enter:

sudo apt-get install build-essential python-dev

  1. Install the library:

sudo python setup.py install

 

3. From raspberry pi start menu go to ‘Programming’ then open ‘Python 3 (IDLE)’.

4. Write the following code:

import time  
import Adafruit_DHT
from serial import Serial

PORT = ‘/dev/ttyUSB0’
BAUD = 9600

ser = Serial(PORT, BAUD)

while True:
    humidity, temperature = Adafruit_DHT.read_retry(11, 4)
    humidity_string = str(humidity) + ‘\n’
    temperature_string = str(temperature) + ‘\n’
    ser.write( ‘The Temperature is : ’.encode())
    ser.write(temperature_string.encode())
    ser.write( ‘The Humidty is : ’.encode())
    ser.write (humidity_string.encode())
    time.sleep(1)

5. Connect the first Xbee to the raspberry pi using the USB dongle.

6. Connect the second Xbee to your and open the arduino serial monitor (this just for check out the results, you can use any other software).

7. Run the code by pressing ‘F5’.

Discussion:

  • We start as always by import the libraries that will make our life easy.
  • For serial communication we first has to know the port our xbee is connected to and the baud rate that you’re going to use. For raspberry pi USB uses port ‘/dev/ttyUSB0’.
  • Then we define a serial object ‘objectName = Serial(PORT , BAUD)’.
  • To send the temperature and humidity we use the command ‘objectName.write()’. Note that this commands takes only binary encoded strings, thus trying to send pure sting or numbers will not work, to send strings and numbers we convert the numbers to strings using the command ‘str()’and we encode the strings using ‘encode()
  • Note: if your only sending a string you can use ‘objectName.write(b‘string’)’, the ‘b’ will tell the library that you want to send the string in binary form.

 

Experiment 3: Xbee Receiver with Raspberry Pi .

In the previous experiment you programmed the raspberry by to transmit to your computer. Receiving data from another Xbee with python is very easy

In this experiment you’ll sending some command to the Raspberry from your computer to switch on an LED.

1. Connect the following Circuit using the shown components

2.Write the following code in the Raspberry Pi:

import RPi.GPIO as GPIO
from serial import Serial
import time

GPIO.setmode(GPIO.BOARD)
GPIO.setup(8,GPIO.OUT)

PORT = '/dev/ttyUSB0'
BAUD = 9600

ser = Serial(PORT, BAUD)
s = ' '

while True:
    s = ser.readline()
    print(s)
    s = s.upper()
    
    if s == 'ON\n':
        GPIO.output(8,GPIO.HIGH)
        
    elif s == 'OFF\n':
        GPIO.output(8,GPIO.LOW)
        
    elif s == 'BLINK\n':
        
        speed = '0'
        Repeation = '0'
        
        ser.write('Set blinking speed in seconds : \n'.encode())
        while speed == '0':
            speed = ser.readline()

        ser.write('Set blinking Repeation : \n'.encode())
        while Repeation == '0':
            Repeation = ser.readline()
            
        for z in range(int(Repeation)):
            GPIO.output(8,GPIO.HIGH)
            time.sleep(float(speed))
            GPIO.output(8,GPIO.LOW)
            time.sleep(float(speed))

3. In your laptop, after installing Python software, open a new script and write the following code:

from serial import Serial

PORT = 'COM4'
BAUD = 9600

ser = Serial(PORT,BAUD)

while True:
    print('Commands List: on, off, blink')
    message = input('Enter command : ')
    message = message
    ser.write(message.encode())
    ser.write(b'\n')
    
    if message.upper() == 'BLINK':
        m = '0'
        while m == '0':
            m = ser.readline()
        print(m)
        speed = input()
        ser.write((speed+'\n').encode())
        
        m2 = '0'
        while m2 == '0':
            m2 = ser.readline()
        print(m2)
        Repeation = input()
        ser.write(Repeation.encode())
        ser.write(b'\n')

4. Open your ‘Device Manager’ and check the XBee COM port.

5. Change the COM port in the code.

6. Run both code, and send a message to the Raspberry Pi.

Discussion:

  • We start as always by import the libraries.
  • As the previous experiment, we set the port and baud rate of the XBee.
  • Then we define a serial object ‘objectName = Serial(PORT , BAUD)’.
  • To receive from the serial we use the command ‘objectName.readline()’. The advantage of ‘readline()’ over ‘read()’ is that the first keeps reading until the ‘\n’, while when using the second you must set the number of bytes you want to read.

 

Experiment 4: UDP server/client.

WiFi is one of the best features of Raspberry Pi. The board connects to the internet with WiFi just like a normal computer. This gives us the opportunity to send and receive data and messages through networks easily and efficiently.

User Datagram Protocol or UDP is one of the internet protocols suits. It’s a way to send data or messages to another devices through Internet Protocol (IP) networks. This protocol sends data in the form of Datagrams (a transfer unit of data). When using UDP to transfer date no connection is required to be established first.

In this experiment you’ll sending messages from your laptop using python software and tehn receiving it and display that message on an LCD.

1. Connect the following Circuit using the shown components

2. Install the LCD library

  1. Run this command in terminal:

git clone https://github.com/adafruit/Adafruit_Python_CharLCD.git

  1. Open the directory:

cd ./Adafruit_Python_CharLCD

sudo python setup.py install

3. After you’ve finished restart the raspberry pi. When the raspberry pi starts again, you can proceed with the experiment. 

4. From raspberry pi start menu go to ‘Programming’ then open ‘Python 3 (IDLE)’.

5. Write the following code in the Raspberry Pi:

import RPi.GPIO as GPIO
import socket
import sys
import Adafruit_CharLCD as LCD
import Adafruit_DHT


lcd = LCD.Adafruit_CharLCD(26, 19, 13, 6, 5, 11, 16, 2, 2)

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #DGRAM for UDP

sock.bind(('192.168.1.8', 9050))


while True:
    data, addr = sock.recvfrom(1024)
    Data_List = list(data)
    print(Data_List)
    for z in range(len(Data_List)):
        if z <= 15:
            lcd.set_cursor(z,0)
            lcd.message(Data_List[z])
        elif z > 15:
            lcd.set_cursor((z-16),1)
            lcd.message(Data_List[z])

6. In your laptop, after installing Python software, open a new script and write the following code:

import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

while True:

    message = input('Massage: ')

    m = bytes(message.encode())

    sock.sendto(m, ('192.168.1.8', 9050))

7. Run both code, and send a message to the Raspberry Pi.

Discussion:

  • As usual, we start by importing the libraries.
  • Then we create an LCD object with the command ‘objectName= LCD.Adafruit_char(pins)’.
  • We also create a socket object with the command ‘objectName= socket.socket(socket.AF_INET, socket.SOCK_DGRAM)’, where ‘DGRAM’stands for Datagram, meaning the we’re going to use UDP.
  • The next step is to bind any not-used port number to the socket with ‘sock.bind( IP, Port))’.
  • Then as always we start an infinite loop.
  • Inside the loop we check for received data ‘sock.recvfrom(buffer size)’. To explain what Buffer size is, first you should understand how data are read. When an incoming data is occurred the data is not read directly into the hard drive or Memory, it first saved bit by bit into a temporary memory ‘Buffer’, once the buffer is full all the data inside of it is passed on and then the buffer take the next portion of data, and so one. The amount of data saved inside the buffer at a time is called ‘Buffer size’.
  • When printing on the LCD, if we try to print a sentence at one time, the LCD will print the first 16 characters of that sentence on the first raw and ignore the rest. To continue on the next line, we convert the sentence in letters with ‘list()’, and then print one character at a time while checking if we reached the end of the line (character number 16), then we write on the next line.

Leave a Comment