The Digital IO Functions provide basic commands to read and write digital values to the IO pins of the microcontroller.
When a pin is set to a digital value of 0 it will have a voltage of 0v, and when a pin is set to a digital value of 1 it will have a voltage of 3.3v. 3.3v is the normal operating voltage of the MSP430 when it is used in the Launchpad board.
In order the use an input or output pin it must first be configured using the pindir command
- pindir( pinname , pintype ) sets the pin direction to be an input (pin is floating)
Then to read and write to the pin use:
- value = inp( pinname ) reads the input pin value ( a 0 or a 1)
- out( pinname , value ) sets the output value to value (0v or 3.3v)
The mpy program will initialize all input pins to be inputs with a pulldown resistor (which is the same as the dirinpd( ) command) This ensures that all pins will be pulled to 0v when the Microcontroller is first started.
pindir(P1_0, OUT) # Set port P1_0 as an output (the Launchpad red led)
pindir(P1_3, INPU) # Set port P1_3 as input with pullup resistor (SW2)
while 1: # do forever
switch_value = inp(P1_3) # read the input from pin P1_3
out(P1_0, switch_value) # set the output pin P1_0 (red led) to switch value
This example will read the Launchpad switch labelled S2 on P1_3 and depending on whether it is pressed or not it will light the red led which is connected to P1_0.
Note input pins which are configured using the pindir( pin, IN ) command will be floating if they are not connected to anything. This means that the voltage at the pin will not be fixed and it will float around (it and will probably pick up stray interference). This can be a problem and cause the microcontroller to draw excessive current and cause other bad effects.
When a mpy program starts it will configure all the unused input pins with pindir( pin, INPD ), this has the effect of making all the pins inputs with pulldown resistors so that if they are unconnected the resistor will pull the input voltage of the pin to 0v, this prevents the pin from floating and causing problems.
So in general it is a good idea to use either pindir( pin, INPD ) , or pindir( pin, INPU ) when setting up your input pins.