c - UART无响应

标签 c microcontroller pic uart

我可以用下面的代码接收,但不幸的是,没有任何东西被发回。我做错了什么?

#include <pic18f25k80.h>
#include "config.h"
#include <usart.h>

int i = 0;
unsigned char MessageBuffer[200];

void main() {
    OSCCONbits.IRCF = 0b110;    // 8MHz
    TRISB6 = 0;                 // TX set as output
    TRISB7 = 0;                 // RX set as output

    // Clear TX interrupt
    // Set RX interrupt
    // 8-bit Asynch. mode
    // BRGH = 1 = high baud mode
    // 51 = ((8MHz/baud)/16)-1   with baud = 9600

    Open2USART(USART_TX_INT_OFF & USART_RX_INT_ON & USART_ASYNCH_MODE
            & USART_EIGHT_BIT & USART_BRGH_HIGH, 51 );

    RC2IF = 0;                  // reset RX2 flag
    RC2IP = 0;                  // not high priority
    RC2IE = 1;                  // Eneble RX2 interrupt
    INTCONbits.PEIE = 1;        // enable peripheral interrupts
    INTCONbits.GIE = 1;         // enable interrupts
    RCSTA2bits.SPEN = 1;        // enable USART

    while(1){
    }
}

void interrupt ISR () {
    if(PIR3bits.RC2IF == 1) {
        if(i<200) {             // buffer size
            MessageBuffer[i] = Read2USART();        // read byte from RX reg
            if (MessageBuffer[i] == 0x0D) {           // check for return key
                puts2USART(MessageBuffer);
                for(;i>0;i--)
                    MessageBuffer[i] = 0x00;        // clear array
                i=0;
                return;
            }
            i++;
            RC2IF = 0;                              // clear RX flag
        } else {
            puts2USART(MessageBuffer);
            for(;i>0;i--)
                MessageBuffer[i] = 0x00;            // clear array
            i = 0;
            return;
        }
    }
}

我正在传输 0x41 十六进制代码,我检查了示波器,发现正在接收。根据我的代码,应该发回接收到的数据的回显。当我检查 TX 引脚时,没有任何反应。

最佳答案

将 USART_CONT_RX 添加到 Open2USART 以启用连续接收。

此外,在中断服务程序中执行最少的必要操作也是个好主意。考虑这样的事情:

void interrupt ISR () {
  char data;

  if(PIR3bits.RC2IF == 1) {
    data = Read2USART();        // always read byte from RX reg (clears RC2IF)
    if(i<200) {                 // buffer size
      MessageBuffer[i] = data;  // read byte from RX reg
      i++;
    }
    else{
      // flag buffer full error
    }
  }
}

然后在 while(1) 循环中完成剩下的工作。

关于c - UART无响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26715186/

相关文章:

c - 使用 C 发送电子邮件

c - LED 条形指示器在相邻值内闪烁以及如何避免这种情况(嵌入式 C)

compiler-errors - CodevisionAVR类型定义

embedded - PIC32 UART 丢弃字节

pic - 免费的 PIC C 编译器

embedded - PIC I2C 从设备确认数据

C编程——从特定的windows目录打开

c - C 中类似 Grep 的过滤器?

c - 如何将具体的二维数组连接到先前定义的指向头文件中指针的指针?

c - .o 文件中 undefined symbol