MSP430 G2553 LaunchPad设置GPIO

 

一. 背景知识:逻辑运算符的使用

当程序初始化时,对于复位状态有不确定性的寄存器(如PxOUT),建议采用直接赋值;其他情况下最好使用逻辑运算符修改寄存器。

直接赋值

REGISTER = 0b11110000;
REGISTER = 0xF0;

“开启”某位(置1),保持其他位不变

REGISTER |= BITx; //turn bit x on
REGISTER |= BITx + BITy; //both on

“关闭”某位(置0),保持其他位不变

REGISTER &= ~BITx; //turn bit x off
REGISTER &= ~(BITx +BITy); //both off

“翻转”某位(取反),保持其他位不变

REGISTER ^= BITx; //toggle bit x
REGISTER ^= BITx + BITy; //toggle both

 

二. GPIO对应的寄存器

如下表所示。

  Register                       Short Form         Register Type         Initial State            
  Input   PxIN   Read only   -
  Output   PxOUT   Read/write   Unchanged
  Direction   PxDIR   Read/write   Reset with PUC

  Pullup/Pulldown

  Resistor Enable

  PxREN   Read/write   Reset with PUC

PxDIR:设置IO管脚的方向

- Bit = 0:输入(默认)

- Bit = 1:输出

PxREN:使能管脚内部上拉/下拉,典型上拉/下拉电阻阻值35kOhm

- Bit=0:禁用上/下拉电阻功能(默认)

- Bit=1:使能上/下拉电阻功能

PxIN:反映管脚上的电平高低

- Bit=0:输入为低电平

- Bit=1:输入为高电平

PxOUT

- 当禁用上/下拉电阻时,功能为设置输出电平高低

- - Bit=0:输出高电平

- - Bit=1:输出低电平

- 当使能上/下拉电阻时,功能为选择上拉还是下拉

- - Bit=0:下拉

- - Bit=1:上拉

特别留意,P2.6、P2.7两个IO口上电默认功能选择为晶体XIN和XOUT,如下图。若要使用P2.6、P2.7的IO功能,需要将P2SEL.6和P2SEL.7置零。

 

三. 初始化程序示例

例1:设置P1.0为输出

 1 #include "io430.h"
 2 
 3 void main(void)
 4 {
 5   // Stop watchdog timer to prevent time out reset
 6     WDTCTL = WDTPW + WDTHOLD;
 7 
 8     P1OUT = 0; //initialize the output state before changing the pin to an output
 9     P1DIR |= BIT0; //P1.0 output 0
10 
11     while(1)
12     {
13         //code...
14     }
15 
16 }

例2:设置P1.3为上拉输入

 1 #include "io430.h"
 2 
 3 #define PUSH2 BIT3
 4 
 5 void main( void )
 6 {
 7     // Stop watchdog timer to prevent time out reset
 8     WDTCTL = WDTPW + WDTHOLD;
 9 
10     P1OUT = 0;
11     P1OUT |= PUSH2; //initialize the pullup state
12     P1REN |= PUSH2; //enable internal pullup
13     P1DIR &= ~PUSH2; //set P1.3 to input mode (default)
14     //state on P1.3: (P1IN & PUSH2) == PUSH2
15 
16     while(1)
17     {
18         //code...
19     }
20   
21 }

参考资料

MSP430x2xx Family User's Guide
MSP430G2553 datasheet

posted @ 2015-06-06 16:08  zelu  阅读(1269)  评论(0编辑  收藏  举报