问题描述
我有一个可以与之通信的串行设备。我决定将代码放入类模块并进行构建。我遇到了有关串行端口的问题。...
错误:
从雷达进口RD
m = RD('S06')
m.KLD2Setup()
回溯(最近通话最近一次):
文件“”,第
行第1行KLD2Setup中的文件“ /home/pi/my_Python/Radar/radar.py”,第23行
s.write(self.cmd.encode())
NameError:名称“ s”未定义
如果我调用python在没有类的文件中创建串行端口等,则此代码块有效
#! /usr/bin/python
class RD():
'''RFB K-LD2 module'''
def __init__(self,command):
'''initialize'''
self.cmd = command
from serial import Serial
s = Serial('/dev/ttyS0',38400)
def KLD2Setup(self):
'''use this method for sending commands and receiving data'''
self.cmd = '$' + self.cmd + '\r'
if (self.cmd[1] in {"S","D","R","W","T"}):
k = 8
elif (self.cmd[1] in {"F","A"}):
k = 10
elif (self.cmd[1] == "C"):
k = input ("Enter the number of bytes? ")
else:
k = 0
if (k):
s.write(self.cmd.encode())
print((s.read(int(k)).rstrip()).lstrip(b'@'))
解决方法
这是一个范围问题,
更改:
第9行:self.s = Serial('/dev/ttyS0',38400)
第23行:self.s.write(self.cmd.encode())
在 init 中创建一个local,然后尝试在方法KLD2Setup中使用local。 当您正在使用一个类时,您需要使用self.s
#! /usr/bin/python
from serial import Serial
class RD():
'''RFB K-LD2 module'''
def __init__(self,command):
'''initialize'''
self.cmd = command
self.s = Serial('/dev/ttyS0',38400)
def KLD2Setup(self):
'''use this method for sending commands and receiving data'''
self.cmd = '$' + self.cmd + '\r'
if (self.cmd[1] in {"S","D","R","W","T"}):
k = 8
elif (self.cmd[1] in {"F","A"}):
k = 10
elif (self.cmd[1] == "C"):
k = input ("Enter the number of bytes? ")
else:
k = 0
if (k):
self.s.write(self.cmd.encode())
print((self.s.read(int(k)).rstrip()).lstrip(b'@'))