Raspberry Pi communication experiment

This article introduces two communication experiments which can be utilized by your Raspberry Pi.

1 USART Serial Communication

Before USB parallel communication becomes ubiquitous, Serial communications like USART protocal are very popular. Even today, these communications protocals are widespread used by the industry.

We plan to use USART 1 for this experiment. Referring to STM32F407 datasheet, PA9 and PA10 are individually used as TX and RX.
Datasheet Page 51

2 Socket communication

Socket communication is a kind of fundamental network communication mothod.Nowadays, Python is very popular so we will do a simple experiment for socket communication between Pi and the computer using python2 socket package.

Socket protocal is like TCT/IP, a two-directional protocal. But it has the design of server and client. We simply take Pi as the server and the computer as the client, neglecting security issues.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#!/usr/bin/env python
# -*- coding:utf-8 -*-

# rand-server.py
import socket
import time
import smbus
import sys
import RPi.GPIO as GPIO

# Init I2C
bus = smbus.SMBus(1)
address = 0x20
# define host ip: RPi's IP
HOST_IP = "192.168.137.244"
HOST_PORT = 8888
print("Starting socket: TCP...")

# 1.Create socket object: socket = socket.socket(family, type)
socket_tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("TCP server listen @ %s:%d!" %(HOST_IP, HOST_PORT))
host_addr = (HOST_IP, HOST_PORT)

# 2.bind socket to addr:socket.bind(address)
socket_tcp.bind(host_addr)

# 3.listen connection request: socket.listen(backlog)
socket_tcp.listen(1)

# 4.wait for client: connection, address = socket.accept()
socket_con, (client_ip, client_port) = socket_tcp.accept()
print("Connection accepted from %s." %client_ip)
socket_con.send("Welcome to RPi TCP server!")

# 5.handle
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT)
while True:
try:
print("Receiving package...")
data = socket_con.recv(512)
if len(data) > 0:
if data == '1':
num = bus.read_byte(address)
print("Received:1, get rand number %d" %num)
time.sleep(1)
socket_con.send(str(num)) # socket data must be string
elif data == '0':
print("Received:0, exit")
GPIO.output(11, GPIO.LOW)
socket_con.close()
# time.sleep(1)
continue
except Exception as e:
print type(e)
print e.args
print e
socket_tcp.close()
sys.exit(1)
FreeBSD survival manual Aug-28th-HackRF-SCCE-access-door-system

Comments

You forgot to set the shortname for Disqus. Please set it in _config.yml.
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×