乐鑫技术交流
直播中

Arvinhw

9年用户 908经验值
擅长:嵌入式技术
私信 关注
[问答]

如何从互联网获取ESP8266时间?

我是一个新手,正在尝试设置一个简单的过程来像大本钟一样根据分秒来操作 2 个伺服系统和 LED。我可以使用这段代码非常简单地连接到我的 wifi 并在串行屏幕上打印分钟和秒;
//从互联网获取ESP8266时间
#include "NTPClient.h"
#include "ESP8266WiFi.h"
#include "WiFiUdp.h"
const char *ssid = "my wifi name";
const char *password = "我的wifi密码";
const long utcOffsetinSeconds = -18000;
//char daysOfTheWeek[7][12] = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};


NTPClient timeClient(ntpUDP, "pool.ntp.org", utcOffsetInSeconds);
void setup(){
Serial.begin(115200);
WiFi.begin(ssid, 密码);
while ( WiFi.status() != WL_CONNECTED ) {
延迟 ( 500 );
Serial.print(".");
}
timeClient.begin();
}
void loop() {
timeClient.update();
//Serial.print(daysOfTheWeek[timeClient.getDay()]);
序列号.print(",");
//Serial.print(timeClient.getHours());
序列号.print(":");
Serial.print(timeClient.getMinutes());
序列号.print(":");
Serial.println(timeClient.getSeconds());
//Serial.println(timeClient.getFormattedTime());
延迟(1000);
}
现在让我感到困惑的部分是,我发现每个使用 wifi 时间运行草图功能的项目都使用从微秒开始的非常复杂和冗长的过程。
有没有简单的方法,直接从wifi读取分秒,在0分-0秒、15分-0秒、30分-0秒、45分-0秒触发草图功能,然后从0开始-分钟,0秒?
分秒组合在串行屏幕中每小时出现一次,为什么我不能只选择这个时间组合并让它触发一个动作?我的应用程序不需要毫秒精度。
我确定我过度简化了这一点,但有人可以帮助我理解。
谢谢

               


                       

回帖(1)

王焕锁

2024-1-4 11:23:13
", "周三", "周四", "周五", "周六"}; WiFiUDP ntpUDP; NTPClient timeClient(ntpUDP, "cn.pool.ntp.org", utcOffsetInSeconds); void setup() { Serial.begin(115200); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi..."); } Serial.println("Connected to WiFi network"); timeClient.begin(); } void loop() { timeClient.update(); Serial.print(timeClient.getMinutes()); Serial.print(":"); Serial.println(timeClient.getSeconds()); delay(1000); }

这段代码可以通过连接到 wifi 并使用 NTPClient 库从 cn.pool.ntp.org 获取时间。您可以将获取的时间用于控制您的伺服和 LED。

在代码中,您可以通过更改 utcOffsetInSeconds 变量来调整 UTC 偏移量,以适应您所在时区的时间。

此外,您还需要使用 Servo 库来控制您的伺服。您可以在 arduino IDE 中打开“工具”菜单,然后选择“库管理器”,搜索“Servo”,然后安装库。然后您可以使用如下代码来控制您的伺服:

#include Servo myservo; // create servo object to control a servo void setup() { myservo.attach(9); // attaches the servo on pin 9 to the servo object } void loop() { myservo.write(angle); // sets the servo position according to the variable angle delay(15); // waits for the servo to reach the position }

您需要将 angle 替换为您想要的角度。类似地,您可以使用 digitalWrite() 来控制您的 LED。您可以将单个 LED 连接到 GPIO 引脚,并使用下面的代码将其控制:

#define LED 13 // define the LED pin void setup() { pinMode(LED, OUTPUT); // sets the pin as output } void loop() { digitalWrite(LED, HIGH); // sets the LED on delay(1000); // waits for a second digitalWrite(LED, LOW); // sets the LED off delay(1000); // waits for a second }

此代码将 LED 置于 gpio13,然后在循环中将其打开和关闭。您可以在 digitalWrite() 内使用变量来根据时间来控制 LED。

希望这些代码对您有所帮助!
举报

更多回帖

发帖
×
20
完善资料,
赚取积分