STM32 uart

uart_init

void uart_init(void){

    GPIO_InitTypeDef GPIO_InitStructure;
    USART_InitTypeDef USART_InitStructure;

    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    //TX
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_InitStructure.GPIO_Pin = UART_TX_PIN;
    GPIO_Init(UART_TX_GRP, &GPIO_InitStructure);

    //RX
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
    GPIO_InitStructure.GPIO_Pin = UART_RX_PIN;
    GPIO_Init(UART_RX_GRP, &GPIO_InitStructure);

    USART_InitStructure.USART_BaudRate = UART_BUADRATE;
    USART_InitStructure.USART_StopBits = USART_StopBits_1;

    USART_InitStructure.USART_WordLength = USART_WordLength_8b;
    USART_InitStructure.USART_Parity = USART_Parity_No;

    USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
    USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;

    USART_Init(UARTx, &USART_InitStructure);
    USART_ITConfig(UARTx, USART_IT_RXNE, ENABLE);   //接收满中断
    USART_ITConfig(UARTx, USART_IT_TXE, DISABLE);   //发送空中断
    USART_Cmd(UARTx, ENABLE);
}

nvic_init

void UartNvicInit(void){

    NVIC_InitTypeDef NVIC_InitStructure;

    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = UART_PREEMPTION_PRIORITY;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = UART_SUB_PRIORITY;

    NVIC_InitStructure.NVIC_IRQChannel = UARTx_IRQn;
    NVIC_Init(&NVIC_InitStructure);
}

stm32f10x_it.c

void UARTx_IRQHandler(void){
    u16 tmp_head;

    if(USART_GetITStatus(USARTx, USART_IT_RXNE) != RESET){
        g_uart_recvbuf[g_uart_recvtail] = USART_ReceiveData(USARTx);
        g_uart_recvtail = (g_uart_recvtail + 1) % UART_RX_BUFSIZE;
    }

    if(USART_GetITStatus(UARTx, USART_IT_TXE) != RESET){
        tmp_head = g_uart_sendhead;
        if(tmp_head == g_uart_sendtail){
            USART_ITConfig(UARTx, USART_IT_TXE, DISABLE);
        }else{
            USART_SendData(UARTx, g_uart_sendbuf[g_uart_sendhead]);
            g_uart_sendhead = (g_uart_sendhead + 1) % UART_TX_BUFSIZE;
        }
    }
}

davice.c


void uart_recvmsg(void){
    u8 ch;
    u16 tmp_tail;

    tmp_tail = g_uart_recvtail;
    if(tmp_tail != g_uart_recvhead){
        ch = g_uart_recvbuf[g_uart_recvhead];
//      printf("%02x, ", ch);
        g_uart_recvhead = (g_uart_recvhead + 1) % UART_RX_BUFSIZE;
        tmp_tail = g_uart_recvtail;
    }
}


void uart_sendbyte(u8 ch){
    u16 tmp_tail;

    tmp_tail = (g_uart_sendtail + 1) % UART_TX_BUFSIZE;
    while(tmp_tail == g_uart_sendhead);

    g_uart_sendbuf[g_uart_sendtail] = ch;

    g_uart_sendtail = tmp_tail;
    USART_ITConfig(UARTx, USART_IT_TXE, ENABLE);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值