通过 UART 从 PIC16F 获取奇怪的输出

Getting strange output from PIC16F over UART

我正在尝试使用 PIC16F15325 打印 hello world 的基本程序。我配置了 PIC 并使用 MPLAB 代码配置器制作了它的库。 函数“EUSART1_Write”如下:

void EUSART1_Write(uint8_t txData)
{
    while(0 == PIR3bits.TX1IF)
    {
    }

    TX1REG = txData;    // Write the data byte to the USART.
}

我为“hello world”编写的代码是这样的:

#include "mcc_generated_files/mcc.h"
void main(void)
{

    // initialize the device
    SYSTEM_Initialize();
    EUSART1_Initialize();
    char n1[] = "Hello world";
    uint8_t i = 0;

    // When using interrupts, you need to set the Global and Peripheral Interrupt Enable bits
    // Use the following macros to:

    // Enable the Global Interrupts
    //INTERRUPT_GlobalInterruptEnable();

    // Enable the Peripheral Interrupts
    //INTERRUPT_PeripheralInterruptEnable();

    // Disable the Global Interrupts
    //INTERRUPT_GlobalInterruptDisable();

    // Disable the Peripheral Interrupts
    //INTERRUPT_PeripheralInterruptDisable();

    while (1)
    {
        // Add your application code
        while(n1[i] != "[=11=]")
        {
            EUSART1_Write(n1[i]);
            DELAY_milliseconds(20);
            i++;
        }
        DELAY_milliseconds(1000);
    }
}

我将 FTDI 电缆的地线连接到 PIC 的地线,将 FTDI 的接收器连接到 PIC 的发射器,将 FTDI 的发射器连接到 PIC 的接收器。波特率 9600,奇偶校验 none,停止位 1。此设置与 PIC 和终端仿真器“TeraTerm”相同。 其余的我按照数据表中的建议连接了 MCLR。 但是我的输出如下:

请帮我想想办法

条件n1[i] != "[=10=]"错误。 "[=11=]" 是一个数组。它被转换为第一个元素的地址,它可能不等于 n1 中的一个元素。您应该与字符行 n1[i] != '[=13=]' 进行比较。

您的代码中有两个错误:

  1. 正如 MikeCAT 已经指出的,条件 n[i] != "[=10=]" 是错误的。编译器应该警告过你比较一个整数(n[i]char 提升)和一个指针("[=13=]" 是一个 char 的数组,这里转换为它的地址第一个元素)。如果不是,请习惯于始终将警告级别提高到最大值。但是您想检查字符串的结尾:n[i] != '[=15=]'.

  2. 在发送字符串的所有字符后,您不会(重新)将 i 设置为零。您可以在内部循环之前执行此操作,我更喜欢这样做,因为它使您的意图清晰,或者在内部循环之后执行此操作,这没问题,因为您已在其定义中对其进行了初始化。