在STC15W4K系列单片机中,与PWM2—PWM7相关的12个I/O口[P3.7/PWM2,P2.1/PWM3,P2.2/PWM4,P2.3/PWM5,P1.6/PWM6,P1.7/PWM7,P2.7/PWM2_2,P4.5/PWM3_2,P4.4/PWM4_2,P4.2/PWM5_2,P0.7/PWM6_2,P0.6/PWM7_2],上电复位后是高阻输入状态,要对外能输出,要软件将其改为强推挽输出或准双向口/弱上拉,与PWM2—PWM7相关的I/O口引脚如下:
配置I/O口为强推挽输出、准双向口/弱上拉、高阻输入和开漏状态如下表格所示:
根据上述单片机I/O口引脚和I/O设置状态表格,用P2口作例子,
(1)将P2端口与PWM相关的I/O配置为强推挽输出用C语言表示如下:
P2M1 = 0x00; //0000 0000B
P2M0 = 0x9E; //1001 1110B
(2)将P2端口与PWM相关的I/O配置为准双向口/弱上拉用C语言表示如下:
P2M1 = 0x00; //0000 0000B
P2M0 = 0x00; //0000 0000B
(3)将P2端口与PWM相关的I/O配置为高阻输入用C语言表示如下:
P2M1 = 0x9E; //1001 1110B
P2M0 = 0x00; //0000 0000B
(4)将P2端口与PWM相关的I/O配置为开漏用C语言表示如下:
P2M1 = 0x9E; //1001 1110B
P2M0 = 0x9E; //1001 1110B
注:以上STC15W4K系列单片机引脚图和I/O设置状态表格是从STC官方下载的STC15W4K系列单片机的数据手册上截取的。
如果想要让STC15W4K系列单片机的所有I/O口与8051单片机的I/O一样,只要把STC15W4K系列单片机的I/O口配置为准双向口/弱上拉即可,我们将上面的STC15W4K系列单片机涉及到的所有端口都配置为准双向口/弱上拉:
P0端口的8个I/O配置为准双向口/弱上拉:P0M1 = 0x00; //0000 0000B
P0M0 = 0x00; //0000 0000B
P1端口的8个I/O配置为准双向口/弱上拉:P1M1 = 0x00; //0000 0000B
P1M0 = 0x00; //0000 0000B
P2端口的8个I/O配置为准双向口/弱上拉:P2M1 = 0x00; //0000 0000B
P2M0 = 0x00; //0000 0000B
P3端口的8个I/O配置为准双向口/弱上拉:P3M1 = 0x00; //0000 0000B
P3M0 = 0x00; //0000 0000B
P4端口的8个I/O配置为准双向口/弱上拉:P4M1 = 0x00; //0000 0000B
P4M0 = 0x00; //0000 0000B
P5端口的8个I/O配置为准双向口/弱上拉:P5M1 = 0x00; //0000 0000B
P5M0 = 0x00; //0000 0000B
我们想用P2端口点亮LED,在开发程序中可以这样写:#include
sbit LED0 = P2^0;
sbit LED1 = P2^1;
sbit LED2 = P2^2;
sbit LED3 = P2^3;
sbit LED4 = P2^4;
sbit LED5 = P2^5;
sbit LED6 = P2^6;
sbit LED7 = P2^7;
void SetPortMode(unsigned char port)
{
switch(port){
case 0:
P0M1 = 0x00;
P0M0 = 0x00;
break;
case 1:
P1M1 = 0x00;
P1M0 = 0x00;
break;
case 2:
P2M1 = 0x00;
P2M0 = 0x00;
break;
case 3:
P3M1 = 0x00;
P3M0 = 0x00;
break;
case 4:
P4M1 = 0x00;
P4M0 = 0x00;
break;
case 5:
P5M1 = 0x00;
P5M0 = 0x00;
break;
}
}
int main(void)
{
SetPortMode(2);
P2 = 0;
LED0 = 0;
LED1 = 0;
LED2 = 0;
LED3 = 0;
LED4 = 1;
LED5 = 1;
LED6 = 1;
LED7 = 1;
while(1);
}