ESP32 Arduino使用Serial.printf()函数

本文介绍在ESP32的Arduino环境中使用printf()函数的方法,通过实例展示如何输出变量值,特别指出在串口监视器中显示中文的能力。同时,文章记录了使用第二硬件串口遇到的问题及初步解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在ESP32中使用printf()函数

在ESP32的Arduino编程中,可以使用printf函数来输出,这在标准的库函数说明中没有提及。其实ESP32的core中是可以使用的。这对调试程序提供了便利!

例子

setup()
{
	Serial.begin(115200);
	int intX = 20;
	Serial.printf("输入的整数 = %d\r\n", intX);
}	

运行结果

运行结果不展示了,注意用Arduino IDE自带的串口监视器可以显示中文。结果是不是很惊奇?

备注

用ESP32采用CH340或者是自己带的串口监视器,串口输出正常,但串口输入不正常,如下:

在这里插入图片描述
有知道的大佬给提示一下,看如何解决!

刚才说的串口不好用是说的第二串口,我用了硬件的第二串口。HardwareSerial, 第二串口的默认外接是rxPin = 16, txPin = 17, 用这个外接端子不好用,换成了rxPin = 4和 txPin = 5. 可以使用了,但通讯的速率只能在9600,发送数据没有问题,接收串口的数据当波特率大于9600时有问题。只能先这样使用了。等解决了告诉大家。

ESP32是一款开源的微控制器开发板,它支持Arduino编程环境。休眠是指将ESP32进入低功耗状态以节省能源的过程。 在ESP32 Arduino中,有多种方式可以实现休眠功能。其中一种方式是使用RTC_GPIO引脚唤醒。通过使用`esp_sleep_enable_timer_wakeup()`函数启用定时器唤醒功能,并设置唤醒时间。然后可以使用`esp_deep_sleep_start()`函数ESP32进入深度睡眠状态。当定时器计时到达时,ESP32将被唤醒。以下是一个示例代码: ```cpp #include <Arduino.h> #include <esp_sleep.h> RTC_DATA_ATTR int bootCount = 0; void setup() { Serial.begin(115200); Serial.printf("ESP32 is restart now! It's the %d time\r\n", bootCount); delay(5000); esp_sleep_enable_timer_wakeup(20000000); Serial.println(esp_sleep_get_wakeup_cause()); } void loop() { Serial.println("ESP32 will sleep now!"); delay(100); esp_deep_sleep_start(); } ``` 还有一种唤醒方式是使用触摸按键唤醒。通过使用`esp_sleep_enable_touchpad_wakeup()`函数启用触摸唤醒功能。然后可以使用`touchAttachInterrupt()`函数将触摸引脚连接到回调函数,当触摸引脚被触摸时,ESP32将被唤醒。以下是一个示例代码: ```cpp #include <Arduino.h> #include <esp_sleep.h> RTC_DATA_ATTR int bootCount = 0; RTC_DATA_ATTR int BTN_Pin_BITMASK = 0; void callbackPin2() { Serial.println("T2 weak ESP32 up"); } void setup() { Serial.begin(115200); Serial.printf("ESP32 is restart now! It's the %d time\r\n", bootCount); esp_sleep_enable_touchpad_wakeup(); Serial.printf("the wakeup reason is :%d\r\n", esp_sleep_get_wakeup_cause()); touchAttachInterrupt(2,callbackPin2,40); } void loop() { delay(3000); Serial.println("ESP32 will sleep now!"); delay(100); esp_deep_sleep_start(); } ``` 此外,还可以使用ULP唤醒方式。通过使用`esp_sleep_enable_ext0_wakeup()`函数启用外部引脚唤醒功能,并设置唤醒的GPIO引脚。当外部引脚状态改变时,ESP32将被唤醒。以下是一个示例代码: ```cpp #include <Arduino.h> #include <esp_sleep.h> RTC_DATA_ATTR int bootCount = 0; void setup() { Serial.begin(115200); Serial.printf("ESP32 is restart now! It's the %d time\r\n", bootCount); esp_sleep_enable_ext0_wakeup(GPIO_NUM_35, 0); Serial.printf("the wakeup reason is :%d\r\n", esp_sleep_get_wakeup_cause()); } void loop() { delay(3000); Serial.println("ESP32 will sleep now!"); delay(100); esp_deep_sleep_start(); } ``` 这些是ESP32 Arduino中实现休眠功能的几种方式。具体使用哪种方式取决于你的需求和硬件环境。希望这些示例代码可以帮助你理解ESP32的休眠功能。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值