How to Fix TypeError: an integer is required in python 3.4, pyserial 2.7 virtual serial port

爷,独闯天下 提交于 2019-12-06 05:43:25

I figure it out, ----------tricky python--------- please pull me up, and check my other questions (with answers of course)

ok first assigning the serial port in a single line will not work as good as

#Method 1
set_ser = serial.Serial(port="COM1", baudrate=9600, parity = serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize = serial.EIGHTBITS, timeout=1)

writing it in this way

#Method 2
set_ser = serial.Serial()
set_ser.port="COM1"
set_ser.baudrate=9600
set_ser.parity = serial.PARITY_NONE
set_ser.stopbits=serial.STOPBITS_ONE
set_ser.bytesize = serial.EIGHTBITS
set_ser.timeout=1

then USE method 2

second tricky part is this line

set_ser.write(temp1.encode('utf-8'))

when Python assign the command .write IT MUST HAVE .endcode() or .encode('utf-8') or ('hex') or ('ascii') etc check this link https://docs.python.org/2/library/codecs.html#standard-encodings and this one http://www.tutorialspoint.com/python/string_encode.htm

now the final code is

def mSend():
  global set_ser, a
  set_ser = serial.Serial()
  set_ser.port="COM1"
  set_ser.baudrate=9600
  set_ser.parity = serial.PARITY_NONE
  set_ser.stopbits=serial.STOPBITS_ONE
  set_ser.bytesize = serial.EIGHTBITS
  set_ser.timeout=1
  print ('Open: ' + set_ser.portstr)
  a = 0
  while a==0:
    temp = input('write open\r\r')
    if (temp == "open"):
      set_ser.close()
      set_ser.open()
      while set_ser.isOpen():
        temp1 = input('Type what you want to send, hit enter:\r\n')
        set_ser.write(temp1.encode('utf-8'))
        if (temp1 == "close"):
          set_ser.close()
          print ('\n\nClosed')
          a = 1
    elif (temp == "close"):
      set_ser.close()
      a = 1
    else:
      print ('unless you write open or close you can not move')

a button can call this function (this code) and it will open the serial port, send data until the user write "close"

you are on windows ... that example is for linux

try serial.Serial("COM1",9600) (its probably not actually at "com1" you will need its actual comN name)

comm ports are enumerated as COM1..99 in windows you can see what it is in the device manager

only put integer, so COM7 set_ser.port= 7 , but actually you must do N-1 so in device manager Windows you see COM7 => pythoncode: set_ser.port= 6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!