首页 > 解决方案 > 带有 USB 任务的 pyserial

问题描述

我需要帮助。目标:例如,基于能量值,根据传感器的温度向用户发送有关高消耗的消息(如果温度低,向用户发送消息,加热器已开启

我对老师的代码有评论,但我不明白它是如何工作的,它是如何编写的

import serial
import time




def connect(port):
    """ Opens the serial port.\n
        Arguments:  port ('/dev/usb0', 'COM11').
    """
    source = serial.Serial(port, 9600, 8, parity='N', timeout=1)
    return source



def idn(port):
    """ Queries the Power Supply IDN. Returns the instrument identification as a string.\n
        Arguments: port number (integer).\n
        Command *IDN??
    """
    #com = 'COM' + str(int(com))
    power_source = connect(port)
    power_source.write(b'*idn?\r\n')
    id = power_source.readline().decode("utf-8")
    print('\nIDN: ', id)
    return()


def settings(port):
    """ Queries the Power Supply settings (Voltage, Current, Output). Returns the settings for OUTPUT1.\n
        Arguments: COM port number (integer).\n
        V<N>?\n
        I<N>?\n
        OP<N>?
    """
    #com = 'COM' + str(int(com))
    power_source = connect(port)
    power_source.write(b'V1?\r\n')
    voltage = power_source.readline().decode("utf-8")
    print('Voltage [V] =', voltage)
    power_source.write(b'I1?\r\n')
    current = power_source.readline().decode("utf-8")
    print('Current [A]=', current)
    power_source.write(b'OP1?\r\n')
    output = power_source.readline().decode("utf-8")
    print('Status Output1 =', output)
    return()



def setup(port):
    """ Sets the Power Supply settings (Voltage, Current). Returns the settings for OUTPUT1.
        Arguments: COM port number (integer).
        V<N> <NRF>
        I<N> <NRF>
    """
    #com = 'COM' + str(int(com))
    power_source = connect(port)
    power_source.write(b'V1 24\r\n')
    power_source.write(b'I1 0.2\r\n')
    return()


def output(port, output):
    """ Sets the OUTPUT1 on/off.
        Arguments: COM port (integer), output (integer, 0 for off, 1 for on)
        command OP<N> <NRF>
    """
    #com = 'COM' + str(int(com))
    power_source = connect(port)
    command = 'OP1 ' + str(output) + '\r\n'
    S = str.encode(command)
    power_source.write(S)
    return()

# Request IDN
port = '/dev/ttyACM1'
idn(port)


# Request voltage setup in the unit
settings(port)

# Set up
setup(port)


# Set up the unit on/off
# output(11, 0)
# settings(11)
#print('All OK')

标签: pythonserial-portpyserial

解决方案


推荐阅读