python读取arduino串口数据_用Python从Arduino读取串行数据

你想把你的连读设置为在后台进行,而不是按需进行。您可以使用threading和Queue。一旦确定有一个有效的值,就可以将串行值添加到队列中,然后套接字调用就会从队列中拉出。会是这样的:from flask import Flask

from flask import render_template

import serial

import json

import random

import threading, Queue

import logging

logging.basicConfig(filename=__file__.replace('.py','.log'),level=logging.DEBUG,format='%(asctime)s [%(name)s.%(funcName)s] %(levelname)s: %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p', filemode='a')

class maxSonarSerialThread(threading.Thread):

def __init__(self, dataQ, errQ, port=None, baudrate=None):

self.logger = logging.getLogger('sonarSerialThread')

self.logger.debug('initializing')

threading.Thread.__init__(self)

self.ser = serial.Serial()

self.ser.timeout = 1

if port is None:

self.ser.port = "/dev/tty.usbserial-A6004amR"

else:

self.ser.port = port

if baudrate is None:

self.baudrate = 115200

else:

self.baudrate = baudrate

#self.ser.flushInput()

self.readCount = 0

self.sleepDurSec = 5

self.waitMaxSec = self.sleepDurSec * self.ser.baudrate / 10

self.dataQ = dataQ

self.errQ = errQ

self.keepAlive = True

self.stoprequest = threading.Event()

self.setDaemon(True)

self.dat = None

self.inputStarted = False

self.ver = ver

def run(self):

self.logger.debug('running')

dataIn = False

while not self.stoprequest.isSet():

if not self.isOpen():

self.connectForStream()

while self.keepAlive:

dat = self.ser.readline()

//some data validation goes here before adding to Queue...

self.dataQ.put(dat)

if not self.inputStarted:

self.logger.debug('reading')

self.inputStarted = True

self.dat.close()

self.close()

self.join_fin()

def join_fin(self):

self.logger.debug('stopping')

self.stoprequest.set()

def connectForStream(self, debug=True):

'''Attempt to connect to the serial port and fail after waitMaxSec seconds'''

self.logger.debug('connecting')

if not self.isOpen():

self.logger.debug('not open, trying to open')

try:

self.open()

except serial.serialutil.SerialException:

self.logger.debug('Unable to use port ' + str(self.ser.port) + ', please verify and try again')

return

while self.readline() == '' and self.readCount < self.waitMaxSec and self.keepAlive:

self.logger.debug('reading initial')

self.readCount += self.sleepDurSec

if not self.readCount % (self.ser.baudrate / 100):

self.logger.debug("Verifying MaxSonar data..")

//some sanity check

if self.readCount >= self.waitMaxSec:

self.logger.debug('Unable to read from MaxSonar...')

self.close()

return False

else:

self.logger.debug('MaxSonar data is streaming...')

return True

def isOpen(self):

self.logger.debug('Open? ' + str(self.ser.isOpen()))

return self.ser.isOpen()

def open(self):

self.ser.open()

def stopDataAquisition(self):

self.logger.debug('Falsifying keepAlive')

self.keepAlive = False

def close(self):

self.logger.debug('closing')

self.stopDataAquisition()

self.ser.close()

def write(self, msg):

self.ser.write(msg)

def readline(self):

return self.ser.readline()

app = Flask(__name__,

static_folder="public",

template_folder="templates")

port = "/dev/tty.usbserial-A6004amR"

dataQ = Queue.Queue()

errQ = Queue.Queue()

ser = maxSonarSerialThread(dataQ, errQ, port=port, ver=self.hwVersion)

ser.daemon = True

ser.start()

@app.route("/")

def index():

return render_template('index.html')

@app.route("/distance")

def distance():

distance = read_distance_from_serial()

return json.dumps({'distance': distance})

def read_distance_from_serial():

a = dataQ.get()

print str(a)

return a

您需要添加一个方法来连接线程以获得一个优雅的退出,但这应该能让您继续

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 这里有一个示例代码可以参考: import serial import MySQLdb # 打开串口 ser = serial.Serial("/dev/ttyUSB0", 9600) # 连接MySQL数据库 db = MySQLdb.connect("localhost", "username", "password", "database") cursor = db.cursor() while True: # 读取串口数据 data = ser.readline() # 将数据写入MySQL cursor.execute("INSERT INTO table_name (data) VALUES (%s)", (data)) # 提交数据 db.commit() ### 回答2: 要用Python代码连接Arduino UNO R3并将数据写入MySQL数据库,你需要进行以下步骤: 1. 首先,你需要确保已经连接好了Arduino UNO R3到计算机上,并且已安装好了Arduino IDE。 2. 在Arduino IDE中,编写一个简单的程序来读取传感器数据(假设我们使用的是温度传感器)。该程序将数据通过串口发送给计算机。 3. 在Python中,你需要安装pyserial库来与Arduino进行串口通信。你可以在终端中运行以下命令来安装pyserial: ```python pip install pyserial ``` 4. 在Python代码中,导入pyserial库并连接到Arduino串口。你需要确定Arduino连接到计算机的串口号,并将其作为参数传递给Serial函数。例如,如果串口号为COM3,代码如下所示: ```python import serial arduino = serial.Serial('COM3', 9600) ``` 5. 接下来,你可以使用arduino.readline()函数来读取来自Arduino数据,并将其存储在变量中。例如,将温度数据存储在变量temperature中: ```python temperature = arduino.readline().decode('utf-8').rstrip() ``` 6. 确保你已经安装了MySQL Connector库,你可以在终端中运行以下命令来安装MySQL Connector: ```python pip install mysql-connector-python ``` 7. 在Python代码中,导入MySQL Connector库并连接到你的MySQL数据库。你需要提供数据库的主机地址、用户名、密码和数据库名称。例如: ```python import mysql.connector mydb = mysql.connector.connect( host="localhost", user="yourusername", password="yourpassword", database="yourdatabase" ) ``` 8. 创建一个游标对象,并使用execute()方法执行插入语句,将读取到的温度数据写入数据库中。例如: ```python mycursor = mydb.cursor() sql = "INSERT INTO temperature (value) VALUES (%s)" val = (temperature,) mycursor.execute(sql, val) mydb.commit() ``` 9. 最后,关闭数据库连接和串口连接。代码如下所示: ```python mycursor.close() mydb.close() arduino.close() ``` 以上是一个简单的Python代码示例,连接到Arduino UNO R3并将数据写入MySQL数据库。当你运行该代码时,你将能够读取Arduino传感器的数据并将其存储在数据库中。请确保在代码中使用正确的串口号、主机地址、用户名、密码和数据库名称。 ### 回答3: 要使用Python代码连接Arduino UNO R3读取数据并将其写入MySQL数据库,您可以遵循以下步骤: 1. 确保您的Arduino UNO R3正确连接到计算机上,并且您已经安装了Arduino IDE来编程控制它。 2. 在Arduino IDE中,编写一个简单的程序来读取传感器数据并将其发送给计算机。例如,您可以使用Serial.println()函数将数据发送到串行端口。确保程序正常运行,并记下Arduino连接的串行端口号。 3. 在计算机上,确保您已经安装了Python和适当的MySQL连接库,比如mysql-connector-python(使用pip install mysql-connector-python命令安装)。 4. 在Python代码中,导入所需的库和模块。例如:import serial(用于与Arduino通信)和import mysql.connector(用于与MySQL数据库通信)。 5. 建立与数据库的连接。使用mysql.connector.connect()函数,并提供数据库的用户名、密码、主机和数据库名称等详细信息。 6. 使用serial.Serial()函数在Python中创建一个串行对象,并传入串行端口号、波特率等参数来与Arduino通信。 7. 在一个无限循环中,使用serial.readline()函数从串行端口读取Arduino发送的数据。将数据转换为适当的格式(例如字符串或数字)。 8. 将读取数据插入到MySQL数据库中。使用mysql.connector的insert语句,将数据插入到数据库中的适当表中。 9. 如果需要,确保及时地提交数据库更改。使用connection.commit()函数提交更改。 10. 关闭与串行端口和数据库的连接。使用serial.close()函数关闭与Arduino的连接,并使用connection.close()函数关闭与MySQL数据库的连接。 这些步骤是一个基本的指导,您可以根据您的需求进一步自定义和优化代码。也可以使用其他Python库和模块来实现此功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值