Read State of an OUTPUT Pin

Discussion about the ZBasic language including the System Library. If you're not sure where to post your message, do it here. However, do not make test posts here; that's the purpose of the Sandbox.
Post Reply
everest
Posts: 96
Joined: 31 May 2010, 9:01 AM

Read State of an OUTPUT Pin

Post by everest »

Is there a simple way to read the current state of an OUTPUT pin in Zbasic? I guess I can assign variables and track that way, but I thought there might be an easier way. Something like:

Code: Select all

If ( Output_Pin = zxOutputLow ) Then
'Do something cool
End If
But that doesn't seem to work. Sorry for the stupid question, but I can't find an answer to this anywhere.

-Jeff
dkinzer
Site Admin
Posts: 3120
Joined: 03 September 2005, 13:53 PM
Location: Portland, OR

Re: Read State of an OUTPUT Pin

Post by dkinzer »

everest wrote:Is there a simple way to read the current state of an OUTPUT pin in Zbasic?
I began to reply to your original post but it was deleted before I finished.

The AVR chip has three registers associated with each I/O port: DDRX, PinX and PortX where X is {A, B, ...}. The DataDirectionRegister (DDR) contains eight bits that individually control whether a given bit of the port is an input (0) or an output (1). The PortX register controls the output state of a given bit if the DDR register indicates that that bit is, indeed, an output. Otherwise, if the bit is an input the PortX bit controls whether the pull-up resistor is enabled or not. Lastly, the PinX register is the means by which a signal present on the I/O line can be read.

The ZBasic system provides some specialized functions that allow you to determine if a given pin is an input or an output and, if an output, what the current state is. The example functions below show how this can be done:

Code: Select all

'
'' PinIsOutput
'
' Determine if a given pin is an output.
'
Function PinIsOutput(ByVal pin as Byte) as Boolean
  PinIsOutput = CBool(Register.DDR(pin) And PortMask(pin))
End Function

'
'' PinOutputState
'
' Determine the current state of a pin (assumed to be an output).
'
Function PinOutputState(ByVal pin as Byte) as Byte
  If CBool(Register.Port(pin) And PortMask(pin)) Then
    PinOutputState= 1
  Else
    PinOutputState= 0
  End If
End Function
Note that you could also use Register.Pin(pin) instead of Register.Port(pin) in the function above. The advantage of doing so is that the former reads the actual state of the pin (including the effects of external circuitry, if any) while the latter simply indicates what the output should be irrespective of the fact that external circuitry might be forcing the pin to a different state.
Last edited by dkinzer on 12 June 2010, 16:13 PM, edited 1 time in total.
- Don Kinzer
everest
Posts: 96
Joined: 31 May 2010, 9:01 AM

Post by everest »

Thanks! This is just what I needed!

-Jeff
Post Reply