TOGGLE

BS1 icon BS2 icon BS2e icon BS2sx icon BS2p icon BS2pe icon BS2px icon

TOGGLE Examples

 

 

 

Syntax: TOGGLE Pin

Function

Invert the state of an output pin.

* Note: expressions are not allowed as arguments on the BS1. The range of the Pin argument on the BS1 is 0–7.

Quick Facts

  BS1 All BS2 models
Affected Register PINS OUTS
Related Commands

HIGH, LOW

Explanation

TOGGLE sets a pin to output mode and inverts the output state of the pin, changing 0 to 1 and 1 to 0.

In some situations TOGGLE may appear to have no effect on a pin's state. For example, suppose pin 2 is in input mode and pulled to +5V by a 10 kΩ resistor. Then the following code executes:

Main:
  DIR2 = 0                              ' pin 2 in input mode
  PIN2 = 0                              ' pin 2 output driver low
  DEBUG PIN2                            ' show state of pin 2
  TOGGLE 2                              ' toggle pin 2 
  DEBUG PIN2                            ' show state of pin 2
  END

Main:
  DIR2 = 0                              ' pin 2 in input mode
  OUT2 = 0                              ' pin 2 output driver low
  DEBUG ? IN2                           ' show state of pin 2
  TOGGLE 2                              ' toggle pin 2
  DEBUG ? IN2                           ' show state of pin 2
  END

The state of pin 2 doesn't change; it's high (due to the pull-up resistor) before TOGGLE, and it's high (due to the pin being output high) afterward. The point is that TOGGLE works on the OUTS register, which may not match the pin's state when the pin is initially an input. To guarantee that the state actually changes, regardless of the initial input or output mode, do this:

  PIN2 = PIN2                           ' make output driver match pin state
  TOGGLE 2                              ' then toggle

  OUT2 = IN2                            ' make output driver match pin state
  TOGGLE 2                              ' then toggle

Go to Welcome page

BASIC Stamp Help Version 2.5.4

Copyright © Parallax Inc.

8/8/2012