Python set Parallel Port data pins high/low

泄露秘密 提交于 2019-12-04 19:42:28

You're talking about a software-hardware interface here. They are usually set low and high by assigning a 1-byte value to a register. A parallel port has 8 pins for data to travel across. In a low level language like C, C++, there would be a register, lets call it 'A', somewhere holding 8 bits corresponding to the 8 pins of data. So for example:

Assuming resgister A is setup like pins: [7,6,5,4,3,2,1,0]

C-like pseudocode

A=0x00 // all pins are set low
A=0xFF // all pins are high
A=0xF0 // Pins 0:3 are low, Pins 4:7 are high

This idea follows through with PyParallel

import parallel
p = parallel.Parallel() # open LPT1
p.setData(0x55) #<--- this is your bread and butter here  

p.setData is the function you're interested in. 0x55 converted to binary is

0b01010101

-or-

[L H L H L H L H]

So now you can set the data to a certain byte, but how would I sent a bunch of data... lets say 3 bytes 0x00, 0x01, 0x02? Well you need to watch the ack line for when the receiving machine has confirmed receipt of whatever was just sent.

A naive implementation:

data=[0x00, 0x01, 0x02]
while data:
    onebyte=data.pop()
    p.setDataStrobe('low') #signal that we're sending data
    p.setData(onebyte)
    while p.getInAcknowledge() == 'high': #wait for this line to go 'low'
                                          # to indicate an ACK
        pass                              #we're waiting for it to acknowledge...
    p.setDataStrobe('high')#Ok, we're done sending that byte.

Ok, that doesn't directly answer your question. Lets say i ONLY want to set pin 5 high or low. Maybe I have an LED on that pin. Then you just need a bit of binary operations.

portState = 0b01100000 #Somehow the parallel port has this currently set
newportState = portState | 0b00010000#<-- this is called a bitmask
print newportState 
>>> 0b011*1*0000

Now lets clear that bit...

newportState = 0b01110000
clearedPin5 = newportState & 11101111
print clearedPin5
>>> 0b011*0*0000

If these binary operations are foreign, I recommend this excellent tutorial over on avrfreaks. I would become intimate with them before progressing further. Embedded software concepts like these are full of bitmasks and bitshifting.

I've made this function to control the pins individually (code derived from here and here):

def setPin(pin,value):
    if(pin==1):
        p.setDataStrobe(value)
    elif(pin>=2 and pin<=9):
        pin = pin-2
        if(value==0):
            # clear the bit
            p.setData(p.getData() & (255 - pow(2, pin)))
        else:
            #set the bit
            p.setData(p.getData() | pow(2, pin))
    elif(pin==14):
        p.setAutoFeed(value)
    elif(pin==16):
        p.setInitOut(value)
    elif(pin==17):
        p.setSelect(value)
    else:
        raise(ValueError("invalid pin number"))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!