zigbee 使用串口来开关来控制灯

#include <ioCC2530.h>

 

#define uint unsigned int

#define uchar unsigned char

 

#define LED1 P0_4 //定义P1_0为LED1的控制引脚

 

 

void Init_LED(); //声明LED初始化函数

void Init_Uart0(); //声明串口0初始化函数

void Init_Cfg_32M(); //声明初始化32M时钟初始化函数

void UR0SendByte(unsigned char Byte);//声明发送一个字节初始化函数

void UR0SendString(unsigned char *str);//声明发送字符串初始化函数

void Execute_CMD(); //声明执行上位机命令初始化函数 

 

char RxBuf; //定义接收缓冲区

char Rx_flag; //定义串口接收标志位

/*====================主函数入口====================*/

void main()

{

  Init_Uart0(); //初始化串口0

  Init_LED(); //初始化LED端口

 

  Init_Cfg_32M(); //初始化32M晶振

  

  UR0SendString(" Hello ZigBee!\r\n");

  

  while(1)

  {

    if(Rx_flag == 1) //是否接收到上位机指令

    {

      

      Execute_CMD(); //判断并执行上位机指令

    }

  }

}

/*===================LED初始化函数==================*/

void Init_LED()

{

  P0SEL &= ~0x10; ; //将P0_4设置为I/O

  P0DIR |= 0x10; //将P0_4端口设置为输出

  LED1 = 0; //关闭LED1灯

 

}

/*==================32M晶振初始化函数===============*/

void Init_Cfg_32M()

{

  CLKCONCMD &= ~0x40; //系统时钟源选择:外部32MHz 。

  while(!(SLEEPSTA & 0x40));//等待晶振稳定

  CLKCONCMD &= ~0x47; //128分频 CLKSPD不发分频

  SLEEPCMD |= 0x04; //关闭不用的RC振荡器

}

/*==================串口0初始化函数=================*/

void Init_Uart0()

{

  PERCFG = 0x00; // USART 0 I/O location: alternative 1 location

    P0SEL = 0x3c; // P0_2, P0_3 as peripheral function

    P2DIR &= ~0xc0; // Port 0 periphera 1st priority: USART 0

 

    U0CSR |= 0x80; // USART mode select: UART mode

 

    /* Baud: 115200 */

    U0GCR |= 11; // BAUD_E

    U0BAUD |= 216; // BAUD_M

 

    UTX0IF = 0; // Clear tx-interrupt flag

    URX0IF = 0; // Clear rx-interrupt flag

    URX0IE = 1; // Enable rx interrupt

    EA = 1; // Enable interrupts

 

    U0CSR |= 0x40; // Enable UART-Rx

}

/*=================串口0接收中断函数=================*/

#pragma vector = URX0_VECTOR

__interrupt void URX0_ISR()

{

  URX0IF = 0; //清中断标志位

  RxBuf = U0DBUF; //将缓冲寄存器的数据给读出来

  Rx_flag = 1; //接收标志位置1

}

/*================串口0发送一个字节函数==============*/

void UR0SendByte(unsigned char Byte)

{

  U0DBUF = Byte; //将要发送的一个字节数据写入U0DBUF

  while(!UTX0IF); //等待TX中断标志,即数据发送完成

  UTX0IF = 0; //清除TX中断标志,准备下一次发送

}

/*================串口0发送字符串函数================*/

void UR0SendString(unsigned char *str)

{

  while(*str != '\0')     

  {

    UR0SendByte(*str++); //逐个发送字符串中的字节

  }

}

/*================执行上位机指令函数=================*/

void Execute_CMD()

{

  Rx_flag = 0; //清0接收标志位

         //如果PC发送00xE1 则点亮LED1 并串口发送字符串

 

  switch(RxBuf){

  case '1':

    LED1 = 1;

    UR0SendString("The LED1 is Open!\r\n");

    break;

  case '2':

    LED1 = 0;

    UR0SendString("The LED1 is Close!\r\n");

    break;

  }

  

}