Python Forum

Full Version: code not working, NameError: name 's' is not defined
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Good afternoon....
I have a serial device that I am able to communicate with. I decided to put the code into a class module and build it out. I am running into an issue with respect to the serial port....

Error:
>>> from radar import RD >>> m = RD('S06') >>> m.KLD2Setup() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/pi/my_Python/Radar/radar.py", line 23, in KLD2Setup s.write(self.cmd.encode()) NameError: name 's' is not defined


My code:
#! /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'@'))
This code block works if I invoke python create a serial port, etc. in a file without a class
this is a scope issue,
change:
  • line 9: self.s = Serial('/dev/ttyS0', 38400)
  • line 23: self.s.write(self.cmd.encode())
In the __init__ you create a local s and try to use a local s in the method KLD2Setup
As you are now using a class you need to use 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'@'))
Thank you both very much...That worked great!
just to mention that brackets in your if/elif/else conditions are redundant

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: