数字量传感器就是只输出高低电平的传感器,例如人体红外传感器,当检测到有人靠近时,IO0脚就输出高电平。霍尔传感器是检测磁场的传感器,当用磁铁靠近时IO0同样输出高电平。声音检测传感器是用来判断外界噪声的,当检测到有噪声,则IO0输出高。各传感器的IO0与单片机的P0.0是连在一起的,单片机通过检查P0.0,来判断传感器的数据。
#include <ioCC2530.h> #include <string.h> #include <stdio.h> #include "DHT11.h" #include "OLED.h" uchar ExternFlag=0; void clock_setup(void) { CLKCONCMD &= ~0x40; //设置系统时钟源为32MHZ晶振 while(CLKCONSTA & 0x40); //等待晶振稳定 CLKCONCMD &= ~0x47; //设置系统主时钟频率为32MHZ } void init_sensor_io(void) { //1.设置IO为普通IO P0SEL |= 0xC0; P1SEL |= 0x07; //2.设置编码口为输入 P0DIR &= ~0xC0; P1DIR &= ~0x07; } uchar get_sensor_id(void) { volatile uchar temp = P0_6<<4|P0_7<<3|P1_0<<2|P1_1<<1|P1_2; return temp; } void set_p0_input(uint bit) { APCFG &= ~(1<<bit); //1.设置IO为普通IO P0SEL &= ~(1<<bit); //2.设置编码口为输入 P0DIR &= ~(1<<bit); } void set_P0_interrupt() { P0DIR &=~0X02; P0_1=0; P0IEN |=0X02; PICTL &=~0X01; IEN1 |=0x20; P0IFG &=~0X02; EA=1; } #pragma vector=P0INT_VECTOR __interrupt void P0_IRQ() { P0IFG &= ~0X02; ExternFlag = 1; P0IF=0; } void main(void) { uint temp16; uchar temp8; uchar buf[16]; uchar* sensor[3]={"人体红外","声音检测","磁场检测"}; clock_setup(); //系统时钟设置,精确延时必须要设置 Delay_ms(1000); //让设备稳定 port_init(); initial_lcd(); init_sensor_io(); set_p0_input(1); //设置P0.1为输入 set_P0_interrupt(); //设置P0.1为外部中断 clear_screen(); //清屏 disp_string_8x16_16x16(1,1,"武汉唯众智创科技"); //显示字符串,括号里的参数分别为(PAGE,列,字符串指针) disp_string_8x16_16x16(3,1,"----实验2.6-----"); Delay_ms(1000); while(1) { clear_screen(); temp8 = get_sensor_id(); switch(temp8){ case 3: //霍尔 sprintf(buf,"SID:%d %s",temp8,sensor[2]); break; case 17: //人体红外 sprintf(buf,"SID:%d %s",temp8,sensor[0]); break; case 20: //声音检测 sprintf(buf,"SID:%d %s",temp8,sensor[1]); break; default: disp_string_8x16_16x16(1,1,"请插入传感器"); disp_string_8x16_16x16(3,1,"----实验2.6-----"); Delay_ms(1000); continue; } disp_string_8x16_16x16(1,1,buf); //显示字符串,括号里的参数分别为(PAGE,列,字符串指针) sprintf(buf,"数字量:%d",ExternFlag); disp_string_8x16_16x16(3,1,buf); if(ExternFlag == 1){ ExternFlag = 0; } Delay_ms(1000); //延时,1S读取1次 } } |