1.1 Python的适用性
2020-05-10 本文已影响0人
Python在工业仪器仪表应用
因本专集集中在Python在工业领域的应用,所以抛开在其他行业的应用不谈。本专集当中仅涉及官方版本的Python,其他发行版本在我有所了解后才会写东西介绍。
- 可以使用pyserial和串口RS232芯片通信 (TTL 3.3v之类的也类似,只是芯片不同)
import serial
# Open port at “9600,8,N,1”, no timeout
ser = serial.Serial('/dev/ttyUSB0') # open Linux serial port
print(ser.name) # check which port was really used
ser.write(b'hello') # write a string
ser.close() # close port
- 可以使用minimalmodbus和RS485芯片通信
#!/usr/bin/env python3
import minimalmodbus
instrument = minimalmodbus.Instrument('/dev/ttyUSB1', 1) # port name, slave address (in decimal)
## Read temperature (PV = ProcessValue) ##
temperature = instrument.read_register(289, 1) # Registernumber, number of decimals
print(temperature)
## Change temperature setpoint (SP) ##
NEW_TEMPERATURE = 95
instrument.write_register(24, NEW_TEMPERATURE, 1) # Registernumber, value, number of decimals for storage
- 可以读写csv文件
import csv
with open('eggs.csv', newline='') as csvfile:
spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in spamreader:
print(', '.join(row))
# output
>>> Spam, Spam, Spam, Spam, Spam, Baked Beans
>>> Spam, Lovely Spam, Wonderful Spam
- 可以操作数据库PyMySQL
import pymysql.cursors
# Connect to the database
connection = pymysql.connect(host='localhost',
user='user',
password='passwd',
db='db',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql, ('webmaster@python.org', 'very-secret'))
# connection is not autocommit by default. So you must commit to save
# your changes.
connection.commit()
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
cursor.execute(sql, ('webmaster@python.org',))
result = cursor.fetchone()
print(result)
finally:
connection.close()
总结:所有基本的需求都可以直接或者外挂一些商用器件来实现
功能 | 实现方式 | 价格 |
---|---|---|
扩展I/O | 树莓派上运行Python程序,调用GPIO Zero | ¥240 |
扩展I/O / PWM驱动 / ADC | 跑Python的主机上(可以是PC/MAC/树莓派等),挂一个Arduino | ¥15~100 |
对于动不动就成千上万的NI LabVIEW软件和板卡来说成本低到吓人。