Article Directory
1. Introduction
Because the project needs to transmit the data detected by the sensor to the PC through the Raspberry Pi, a simulation experiment was carried out on the communication between the Raspberry Pi and the PC. The experiment used the Raspberry Pi as the client and Socket
the PC as the server. Send data and pymysql
insert the received data into the local database.
2. Hardware preparation
1. Raspberry Pi 4B * 1
2. Network cable * 1
Because it communicates through a local area network, it needs to be connected to a PC or a router with a network cable. If you want to communicate wirelessly, you can build a cloud server, which can be implemented by calling the cloud server. I won't introduce too much here.
If you do not know how to connect the PC via cable students can refer to the Raspberry Pi 4B a network cable directly connected PC
Three, software preparation
When running the program, run the PC first, and then run the Raspberry Pi.
1. PC (server)
import pymysql # 导入 pymysql
import socket
import time
print("服务端开启")
# 套接字接口
mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 设置IP和端口
host = '192.168.137.1'
port = 2222
# bind绑定该端口
mySocket.bind((host, port))
mySocket.listen(10)
# 打开数据库连接
db = pymysql.connect(
host='localhost',
port=3306,
user='root',
passwd='123456',
db='skdb',
charset='utf8'
)
print("数据库开启")
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
sqltime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
while True:
# 接收客户端连接
print("等待连接....")
client, address = mySocket.accept()
print("新连接")
print("IP is %s" % address[0])
print("port is %d\n" % address[1])
while True:
# 读取消息
msg = client.recv(1024)
# 把接收到的数据进行解码
print(msg.decode("utf-8"))
print("读取完成")
# SQL 插入语句
# sql = "INSERT INTO MAGNETISM(MTIME , MFLAG) VALUES ('%s','%s')" % (sqltime, msg.decode("utf-8"))
sql = "INSERT INTO MAGNETISM(MFLAG) VALUES ('%s')" % (msg.decode("utf-8"))
try:
# 执行sql语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except:
# 如果发生错误则回滚
db.rollback()
time.sleep(10)
if msg == "over":
client.close()
mySocket.close()
# 关闭数据库连接
db.close()
print("程序结束\n")
exit()
2. Raspberry Pi (client)
import socket
import time
print("客户端开启")
#套接字接口
mySocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#设置ip和端口
host = '192.168.137.1'
port = 2222
try:
mySocket.connect((host, port)) ##连接到服务器
print("连接到服务器")
except : ##连接不成功,运行最初的ip
print ('连接不成功')
while True:
#发送消息
msg = '9'
#编码发送
mySocket.send(msg.encode("utf-8"))
print("发送完成")
time.sleep(10)
if msg == "over":
mySocket.close()
print("程序结束\n")
exit()
print("程序结束\n")
3. Experimental results
The client sends simulated data 9 to the server every 10 seconds, and the server receives it and stores it in the mysql database.
Database Table:
Four, summary of the problem
1. Socket of Python realizes interactive communication between PC and Raspberry Pi
The Socket communication part of Raspberry Pi and PC refers to this article of Socket of Python to realize the interactive communication between PC and Raspberry Pi . It realizes that the PC sends data to the Raspberry Pi. I changed it to the Raspberry Pi in turn. The PC sends data.
2. The pymysql database connection problem given by the rookie tutorial
The connect error in the example given in the rookie tutorial may be out of date or something, I don’t know.
#!/usr/bin/python3
import pymysql
# 打开数据库连接
db = pymysql.connect("localhost","testuser","test123","TESTDB" )
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 使用 execute() 方法执行 SQL 查询
cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法获取单条数据.
data = cursor.fetchone()
print ("Database version : %s " % data)
# 关闭数据库连接
db.close()
Modify it to the following:
# 打开数据库连接
db = pymysql.connect(
host='localhost',
port=3306,
user='root',
passwd='123456',
db='skdb',
charset='utf8'
)
Databases, users, etc. need to be changed to their own.
3. The problem that pymysql inserts variable with parameters does not display
Just change the ordinary insert statement to the following: (At the same time pay attention to the placeholder and double quotation marks)