-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpython
65 lines (50 loc) · 1.34 KB
/
python
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
60
61
62
63
64
65
create table data(id int not null auto_increment,
create_time timestamp NOT NULL DEFAULT NOW(),
value TEXT,
PRIMARY KEY (`id`)
);
#coding=utf-8
import pymysql
import serial
from time import sleep
# 打开数据库连接
db = pymysql.connect("localhost","root","samsung","test" )
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
def insertDb(value):
data=value
# 使用 execute() 方法执行 SQL 查询
sqlString = "insert into data(value) values('" +data+"')"
try:
# 执行sql语句
cursor.execute(sqlString)
# 提交到数据库执行
db.commit()
print("insert ok")
except:
# 如果发生错误则回滚
db.rollback()
print("insert error")
# 关闭数据库连接
db.close()
def recv(serial):
while True:
data = serial.read_all()
if data == '':
continue
else:
break
sleep(0.02)
return data
if __name__ == '__main__':
serial = serial.Serial('COM9', 9600, timeout=0.5) #/dev/ttyUSB0
if serial.isOpen() :
print("open success")
else :
print("open failed")
while True:
data =recv(serial)
if data != b'' :
print("receive : ",data)
insertDb(data)
serial.write(data) #数据写回