在 for 循环中初始化的变量包含一个值,不会增加

问题描述

我正在为 STM32 微控制器开发一个函数,该函数通过 uart 端口发送给定长度的字符串。为了处理 uart 通信,我创建了一个 Serial 类,该类具有在中断处理程序中弹出和传输的传输和接收缓冲区。我目前正在研究的函数实际上是我之前编写的有效函数的重载。下面是工作函数

void Serial::sendString(char* str) {
// Writes a string to txBuffer. If Transmit interrupts are enabled,and
// the Data register is empty,the txBuffer will be popped into the DR to
// prime the interrupts.

__HAL_UART_disABLE_IT(uart,UART_IT_TXE); // Keeps our spaghetti straightened out...

while (*str != '\0') { // While char is not a null terminator...
    txBuffer->push(*str); // Push first char into queue as we kNow it is valid
    str++; // Pointer goes to next char in string
}

 uint32_t isrflags   = READ_REG(uart->Instance->SR); // Reads the flags and control register
 //uint32_t cr1its     = READ_REG(uart->Instance->CR1); // Into variables

 // If the DR is empty and Transmission interrupts are disabled...
 if ((isrflags & USART_SR_TXE) != RESET) {
    uart->Instance->DR = txBuffer->pop(); // Reenable interrupts and prime the DR
    }

 __HAL_UART_ENABLE_IT(uart,UART_IT_TXE); // Alright,time to cook the pasta

}

重载是我遇到问题的功能。出于某种原因,调试器显示变量“i”初始化为值“14”,并且在调试器单步执行时不会增加。事实上,调试器根本不允许我进入 for 循环。这是重载:

void Serial::sendString(char* str,unsigned int len) {
// Writes a string to txBuffer. If Transmit interrupts are enabled,the txBuffer will be popped into the DR to
// prime the interrupts.
// Rather than being terminated by a null character,this method instead
// sends each char in an array of a specified length. Note that this overload
// MUST be used in any situation that a null terminator might appear in a char
// array!

__HAL_UART_disABLE_IT(uart,UART_IT_TXE); // Keeps our spaghetti straightened out...

for (unsigned int i = 0; i < len; i++) { // While char is not a null terminator...
    txBuffer->push(str[i]); // Push first char into queue as we kNow it is valid
    //str++; // Pointer goes to next char in string
}

 uint32_t isrflags   = READ_REG(uart->Instance->SR); // Reads the flags and control register
// uint32_t cr1its     = READ_REG(uart->Instance->CR1); // Into variables

 // If the DR is empty...
 if ((isrflags & USART_SR_TXE) != RESET) {
    uart->Instance->DR = txBuffer->pop();
    }
 __HAL_UART_ENABLE_IT(uart,time to cook the pasta

}

这些函数在 main 中的一个终端 while 循环中被调用。调试时,问题立即发生;我根本无法承受超载。我的代码似乎只是在这个位置停了下来。

我之前已经能够成功运行重载。这个错误只在我试图解决函数中的另一个错误时出现,其中字符串中的第一个字符只在一半时间内被传输。我设置了一个断点并开始调试,现在它根本无法工作......

解决方法

听起来编译器已经优化掉了你的循环控制变量。

如果您启用了高级别的优化,那么可以展开循环,或者如果您从定义它的同一个文件中调用该函数,则可以将其内联以消除循环控制变量。

您实际上还没有描述您尝试调试的问题是什么。与其期望调试体验是完美的,不如尝试解决您遇到的问题,尽管我总是 14 岁!

仅查看您发布的代码,我看不出有什么大问题。您没有显示的代码中当然可能存在错误。

我强烈反对这种无用的评论,即这段代码从根本上说是垃圾。打开和关闭中断以访问共享数据是过时且低效的,但也很简单,可能足以满足您的目的。

在此函数中将第一个字节写入 UART 确实为您节省了一个中断的成本,但是如果您正在写入 20 个字节的字符串,您真的关心是否需要 20 个或 19 个中断来执行此操作吗?一个好的设计原则是,只有当代码获得了你不想没有的东西时,你才应该让代码变得更复杂。