I am trying to write a code for displaying numbers on a four digit seven segment display using STM32-F401RE. The problem lies in the while(1) loop.
Here is the code:

void num_display_func(uint16_t numtodisplay);
void displayDigit(uint8_t number);

int main(void){
while (1)
  {
    /* USER CODE END WHILE */
      num_display_func(0209);
    /* USER CODE BEGIN 3 */
  }


void num_display_func(uint16_t numtodisplay){

    uint8_t digit_extract[4];

    digit_extract[0] = numtodisplay%10;       //extract the last digit of the number
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_9, SET);
    displayDigit(digit_extract[0]);
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_9, RESET);

    HAL_Delay(10);

    digit_extract[1] = (numtodisplay/10)%10;  //extract the second last digit
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_10, SET);
    displayDigit(digit_extract[1]);
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_10, RESET);

    HAL_Delay(10);

    digit_extract[2] = (numtodisplay/100)%10; //extract the third last digit
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_11, SET);
    displayDigit(digit_extract[2]);
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_11, RESET);

    HAL_Delay(10);

    digit_extract[3] = (numtodisplay/1000)%10; //extract the fourth last digit
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_12, SET);
    displayDigit(digit_extract[3]);
    HAL_GPIO_WritePin(GPIOA, GPIO_PIN_12, RESET);

    HAL_Delay(10);

}

void displayDigit(uint8_t number){


    GPIOC->ODR |= GPIOx_SEGMENTS_MASK;  //Clear the segment bits (Setting the bits to HIGH for common Anode config)

    uint8_t digit = segmentCodes[number];

    GPIOC->ODR |= (digit & GPIOx_SEGMENTS_MASK );

}

当我try 运行代码时,出现以下错误:

./Core/Src/main.c:115:21: error: invalid digit "9" in octal constant
  115 |    num_display_func(0209);
      |                     ^~~~

据我所知,如果删除0,这个问题就可以修复.但在这种情况下,如何显示数字0209或任何其他以零开始的数字呢?

如果我从数字中删除0,它可能会显示209而不是0209.如何解决这个问题?

推荐答案

Octal个有效值是0-7 - 8位数字,以8为底.因此,0209not是有效的八进制数.这就是您的编译器抱怨的原因.八进制0209不存在,您能得到的最接近的是0207,然后是0210、0211(这将是"等效的").因此,编译器试图将convert 0209 octal进行小数,以便将该数字作为参数传递,但失败了,因为9不是有效数字.

此外,在您的num_display_func中,您将数字转换为一个小数(除以10、num_display_funcnum_display_func0.并将其余部分作为% 10).所以你有问题.

如果我从数字中删除0,它可能会显示209而不是0209.如何解决这个问题?

您在硬件中测试过这一点吗?因为如果您仅通过209,程序应该正确地将零放入其中.

1st digit: 209 % 10 == 9
2nd digit: (209 / 10) % 10 == 20 % 10 == 0
3rd digit: (209 / 100) % 10 == 2 % 10 == 2
4th digit: (209 / 1000) % 10 == 0 % 10 == 0

因为你are在所有四位数字上写入硬件,所以数字零将被写入.

C++相关问答推荐

插入元素后,Sizeof操作符无法正常工作

如何将匿名VLA分配给指针?

为什么这个select()会阻止?

设计处理各种数据类型的方法和数据 struct

通过管道将一个子系统的标准输出发送到另一个子系统的标准输出

具有交换链获取和命令缓冲区提交的同步-危险-读后写错误

我怎么才能用GCC编译一个c库,让它包含另一个库呢?

对重叠字符串使用MemMove

S的这种管道实施有什么问题吗?

编译器如何处理具有更复杂值的枚举?

C整型和_泛型.哪些类型是兼容的?

将多项式从文件.txt加载到终端时出现问题

为什么我在C代码中得到一个不完整的类型?

合并对 struct 数组进行排序

`预期说明符-限定符-列表在‘(三元运算符中的’token`‘之前

如何在不更改格式说明符的情况下同时支持双精度和长双精度?

浮点正零何时不全为零?

C struct 中的冒泡排序

10 个字节对于这个 C 程序返回后跳行的能力有什么意义

多行表达式:C 编译器如何处理换行符?