串口

2020-07-27  本文已影响0人  昨天剩下的一杯冷茶
#include <iocc2540.h>
#include "uart.h"


void setting_baudrate(unsigned long baudrate)
{
  switch(baudrate)
  {
    case 115200:
      U0GCR = 11;                       
      U0BAUD = 216;              //波特率设为115200
    break;
    case 9600:
      U0GCR = 8;                       
      U0BAUD = 59;              //波特率设为9600
    break; 
    default:
      U0GCR = 9;                       
      U0BAUD = 59;              //波特率设为9600
    break;   
  
  }
}
void uart_init(void)
{
  CLKCONCMD &= ~(1<<6);//设置系统时钟源为 32MHZ 晶振
  while(CLKCONSTA & (1<<6));//等待晶振稳定为 32M
  CLKCONCMD &=~((1<<6)|(7<<0));//设置系统主时钟频率为 32MHZ
  
  PERCFG = 0x00;
  P0SEL |=(0xf<<2);
  P2DIR &= ~(3<<6);
  U0CSR |= 1<<7;//USART mode select 0: SPI mode 1: UART mode
  
  setting_baudrate(115200);
  UTX0IF=0;
  U0CSR |=1<<6;//UART receiver enable. Note: Do not enable receive before UART is fully configured.0: Receiver disabled 1: Receiver enabled
  
  //enable irq
  URX0IE=1;
  EA=1;  
  
  
}
void uart_send(char *p,int len)
{
  unsigned int i;
  for (i=0; i<len; i++)
  {
    U0DBUF = p[0];
    p++;
    while(!UTX0IF);
    UTX0IF=0;
  }
}

unsigned char cmd;
#pragma vector=URX0_VECTOR
__interrupt void URX0_ISR(void)
{
  cmd=U0DBUF;
  URX0IF=0;
}


//main.c
#include "led.h"
#include "timer.h"
#include "uart.h"
/*
UART0 对应的外部设备 IO 引脚关系为: P0_2 ------ RX
                                     P0_3 ------ TX
UART1 对应的外部设备 IO 引脚关系为: P0_5 ------ RX
                                     P0_4 ------ TX
*/
void main(void)
{

  
  led_init();
  timer1_init();
  uart_init();
  uart_send("hello world\r\n",sizeof("hello world\r\n"));
  while(1)
  {
      switch(cmd)
      {
        case 0x00:
          LED1_OFF
          LED2_OFF
          LED3_OFF
          uart_send("close all led\r\n",sizeof("close all led\r\n"));
          cmd=0xff;
        break;
        
        case 0x01:
          LED1_ON
          LED2_OFF
          LED3_OFF
          uart_send("open led1\r\n",sizeof("open led1\r\n"));
          cmd=0xff;
        break;
        case 0x02:
          LED1_OFF
          LED2_ON
          LED3_OFF
          uart_send("open led2\r\n",sizeof("open led2\r\n"));
          cmd=0xff;
        break;
        case 0x03:
          LED1_OFF
          LED2_OFF
          LED3_ON
          uart_send("open led3\r\n",sizeof("open led3\r\n"));
          cmd=0xff;
        break;
      }


  }
}
image.png
上一篇下一篇

猜你喜欢

热点阅读