esp32之hello_world分析

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fengfeng0328/article/details/82818655

1.esp-idf里面有一个名字example的文件夹,里面有很多乐鑫例程,可通过里面例程入门esp32,首先看一下hello_world:

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "esp_spi_flash.h"


void app_main()
{
    printf("Hello world!\n");

    /* Print chip information */
    esp_chip_info_t chip_info;
    esp_chip_info(&chip_info);
    printf("This is ESP32 chip with %d CPU cores, WiFi%s%s, ",
            chip_info.cores,
            (chip_info.features & CHIP_FEATURE_BT) ? "/BT" : "",
            (chip_info.features & CHIP_FEATURE_BLE) ? "/BLE" : "");

    printf("silicon revision %d, ", chip_info.revision);

    printf("%dMB %s flash\n", spi_flash_get_chip_size() / (1024 * 1024),
            (chip_info.features & CHIP_FEATURE_EMB_FLASH) ? "embedded" : "external");

    for (int i = 10; i >= 0; i--) {
        printf("Restarting in %d seconds...\n", i);
        vTaskDelay(1000 / portTICK_PERIOD_MS);
    }
    printf("Restarting now.\n");
    fflush(stdout);
    esp_restart();
}

看完hello_world也总要学点东西吧:

1.#include <stdio.h>可以看出来该SDK是依赖标准C库

2.#include "freertos/FreeRTOS.h"可以看出来该SDK定义为FreeRTOS系统,即嵌入式实时操作系统RTOS
   #include "freertos/task.h"

3.void app_main(){}可以看出app_main是程序入口函数,也是我们所说的主函数main

4.vTaskDelay(1000 / portTICK_PERIOD_MS)是FreeRTOS里面的常用延迟函数,这函数有一定的研究价值,后面讨论

5.fflush(stdout)的使用很细心,乐鑫代码水平还是不错的

分析fflush(stdout)的使用:

printf是一个行缓冲函数,先写到缓冲区,满足条件后,才将缓冲区刷到对应文件中,刷缓冲区的条件如下:    

1 )缓冲区填满    

2 )写入的字符中有'\n'     

3 )调用fflush手动刷新缓冲区    

4 )调用scanf要从缓冲区中读取数据时,也会将缓冲区内的数据刷新

有人问为何我以前程序没有添加'\n'也能顺利打印出来,因为你printf不是在一个循环里面,便也不会牵扯到问题,因为就算执行printf后只是将内容送到缓冲区,但是你到程序结束里,程序结束便会导致缓冲区刷新,你便看到你到屏幕上有你期望到东西出现了,当然,经过测试,这也是跟编译器有关,但在while里面使用printf是跟上一句fflush(stdout)是保险的做法,手动刷新缓冲区,避免造成不必要的bug

最后,这代码分析到这里,可以尝试运行你的第一个hello_world demo

猜你喜欢

转载自blog.csdn.net/fengfeng0328/article/details/82818655