基於Python的串口通信(2)
2 pyvisa
2.1 安裝pyvisa
2.1.1 source安裝
(1) 下載pyvisa
① 說明文檔:
http://pyvisa.readthedocs.org/en/latest/
② 下載鏈接:
?https://github.com/hgrecco/pyvisa
?http://pyvisa.sourceforge.net/
(2) 解壓
① 命令解壓
cd /xxx/xxx/pyvisa-master.zip(切換到相關文件所在目錄)tar zxvf pyvisa-master.zip
② 手動解壓(Mac下像.zip類的格式一般會在Safari下載完成後自動解壓)
(3) 安裝visamodule
cd /xxx/xxx/pyvisa-master(切換到解壓後的文件所在目錄)sudo python setup.py install(加sudo以避免許可權問題:」Permission denied...」)
註:pyvisa 是依託於enum34的,如果是首次安裝,還需要先下載enum34並安裝:
https://pypi.python.org/pypi/enum34/1.0.4
安裝方法同上:
2.1.2 pip安裝
sudo pip install pyvisa
註:上圖中之所以寫成pip3.5(pip/pip3)是因為系統里除了自帶的Python2外,還裝了Python3(pip3為默認pip)。
2.2 安裝NI-VISA
pyvisa是基於NI-VISA庫的,所以要正常的使用,還需要安裝NI的VISA庫:
http://www.ni.com/visa/
下載鏈接:
http://www.ni.com/download/ni-visa-14.0.1/5023/en/
2.3 visa通信測試
2.3.1 USB模式
在IDLE中進行如下測試:
>>> import visa>>> rm = visa.ResourceManager()>>> rm.list_resources()(uUSB0::0x0957::0x1A07::MY53203784::INSTR,)>>> my_instrument = rm.open_resource(USB0::0x0957::0x1A07::MY53203784::INSTR)>>> print(my_instrument.query(*IDN?))Agilent Technologies,34461A,MY53203784,A.01.09-02.25-01.09-00.35-01-01>>>
附:一個簡單的測試腳本(.py文件)
#!/usr/bin/env python# -*- coding: utf-8 -*-import visafrom pyvisa.resources.usb import USBInstrumentfrom pyvisa.constants import *rm = visa.ResourceManager()res = rm.list_resources()#print rm#print res#print(len(res))if len(res) > 0: # print(res[0]) for dev in res: dev_name = str(dev) if dev_name.startswith("USB"): print("usb resource") usb_res = USBInstrument(rm, dev_name) usb_res.open() #usb_res = rm.open_resource(res[0]) idn = usb_res.query("*IDN?") print(idn) print("over") #關閉串口 usb_res.close() else: print("other resources")else: print("no dev found")
1.3.2 LAN模式
在IDLE中進行如下測試:
>>> import visa>>> rm = visa.ResourceManager()>>> rm.list_resources()(uTCPIP0::A-34461A-03784.local::inst0::INSTR,)>>> my_instrument = rm.open_resource(TCPIP0::A-34461A-03784.local::inst0::INSTR)>>> print(my_instrument.query(*IDN?))Agilent Technologies,34461A,MY53203784,A.01.09-02.25-01.09-00.35-01-01>>>
附:一個簡單的測試腳本(.py文件)
#!/usr/bin/env python# -*- coding: utf-8 -*-import sys, os, visa, threading, timePM = visa.instrument("TCPIP0::192.168.1.70::inst0::INSTR")def check_read(): #currentdir = os.curdir #fullname = os.path.join(currentdir, "read_pm.txt") #fullname = os.path.join(".", "read_pm.txt") if os.path.isfile("read_pm.txt"): read_pm() os.remove("read_pm.txt") returndef read_pm(): PM.write("FETCh:CW:POWer?") # Write file fpm_read = open("pm_read_ok.txt","w") fpm_read.write(PM.read()) fpm_read.close() returndef main(): # Display ID print PM.ask("*IDN?") # Init PM PM.write("*CLS") # Main loop while 1: time.sleep(1) check_read()if __name__ == __main__: main()
推薦閱讀: