A Python interface to a large-format pen plotter

The plotter Class

The plotter class represents the actual plotter hardware (Listing 3). Line 225 defines the __init__ function, which requires the port address to open to reach the plotter. It initializes an instance of the serial class to create the connection to the plotter (line 226).

Listing 3

plotter Class

224 class plotter:
225    def __init__ ( self , port ):
226       self.port = serial.Serial ( port , 9600 )
227    def getPaper ( self ):
228       self.port.write ( "OP" )
229       chunk = ""
230       while 1:
231          char = self.port.read ( 1 )
232          if char != "\r": chunk += char
233          else: break
234       size = chunk.split ( "," )
235       return ( int ( size [ 0 ] ) , int \
                  ( size [ 1 ] ) , int ( size [ 2 ] ) , int ( size [ 3 ] ) )
236
237    def getBuffer ( self ):
238       self.port.write ( chr ( 27 ) + ".B" )
239       chunk = ""
240       while 1:
241          char = self.port.read ( 1 )
242          if char != "\r": chunk += char
243          else: break
244       return int ( chunk )
245

The getPaper function on line 227 sends OP to the plotter (line 228), which says "tell me about the paper you have loaded." Lines 229-233 read characters back from the plotter one at a time (line 231) and either append them to chunk (line 232) or exit the receive loop (line 233) if the character is a carriage return. Once the entire string has been received, it is split by commas (line 234) and returned as a four-part tuple (line 235). These integers represent the size of the paper in "plotter units" with 0,0 in the center and positive values moving up/right and negative values moving down/left.

Lines 237-244 define the getBuffer function. This works almost identically to getPaper, except that since only one value is returned the end result doesn't have to be split.

The nullPlotter and nullSerial Classes

I assume that most readers don't have a pen plotter directly available to them, and this exercise would be kind of boring if you couldn't try things out. So, the null classes (Listing 4) allow this. The classes define the same set of functions as plotter and return default values when requested. This will allow you to try the program without first purchasing a plotter.

Listing 4

nullPlotter and nullSerial Classes

246 class nullPlotter:
247    def __init__ ( self , port ):
248       self.port = nullSerial()
249    def getPaper ( self ):
250       return ( -16384 , -10000 , 16384 , 10000 )
251    def getBuffer ( self ):
252       return 1024
253
254 class nullSerial:
255    def write ( self , cmd ):
256       time.sleep ( .01 )
257       pass
258

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy Raspberry Pi Geek

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content