无法通过 USB 将计算机时间同步到 Arduino [英] Unable to sync computer time to Arduino via USB
问题描述
我想将时间从我的电脑同步到 arduino.我正在使用他们的时间库,但它不起作用.
I want to sync the Time from my pc to the arduino. I am using their Time library but it does not work.
我怎样才能让 arduino 和我的电脑有相同的时间?我目前使用的是 mac.
How can I get the arduino to have the same time as on my computer ? I am currently using a mac.
他们的文档说:
在 unix 系统上,您可以使用 shell 命令设置时间:
On a unix system, you can set the time with the shell command:
TZ_adjust=-8;echo T$(($(date +%s)+6060$TZ_adjust)) >/dev/tty.usbserial-A8008pym
我在终端上试过
>export TZ_adjust=-8; echo T$(($(date +%s)+6060$TZ_adjust)) > /dev/tty.usbmodemfd131
我得到权限被拒绝.
我做错了什么?有没有更简单的方法可以将 arduino 上的时间与我的电脑同步?
What am I doing wrong? Is there a simpler way to sync the time on arduino with my computer?
代码
#include <Time.h>
#define TIME_MSG_LEN 11 // time sync to PC is HEADER followed by unix time_t as ten ascii digits
#define TIME_HEADER 'T' // Header tag for serial time sync message
#define TIME_REQUEST 7 // ASCII bell character requests a time sync message
void setup() {
Serial.begin(9600);
setSyncProvider( requestSync); //set function to call when sync required
Serial.println("Waiting for sync message");
}
void loop(){
if(Serial.available() )
{
processSyncMessage();
}
if(timeStatus()!= timeNotSet)
{
digitalWrite(13,timeStatus() == timeSet); // on if synced, off if needs refresh
digitalClockDisplay();
}
delay(1000);
}
void digitalClockDisplay(){
// digital clock display of the time
Serial.print(hour());
printDigits(minute());
printDigits(second());
Serial.print(" ");
Serial.print(day());
Serial.print(" ");
Serial.print(month());
Serial.print(" ");
Serial.print(year());
Serial.println();
}
void printDigits(int digits){
// utility function for digital clock display: prints preceding colon and leading 0
Serial.print(":");
if(digits < 10)
Serial.print('0');
Serial.print(digits);
}
void processSyncMessage() {
// if time sync available from serial port, update time and return true
while(Serial.available() >= TIME_MSG_LEN ){ // time message consists of a header and ten ascii digits
char c = Serial.read() ;
Serial.print(c);
if( c == TIME_HEADER ) {
time_t pctime = 0;
for(int i=0; i < TIME_MSG_LEN -1; i++){
c = Serial.read();
if( c >= '0' && c <= '9'){
pctime = (10 * pctime) + (c - '0') ; // convert digits to a number
}
}
setTime(pctime); // Sync Arduino clock to the time received on the serial port
}
}
}
time_t requestSync()
{
Serial.print(TIME_REQUEST,BYTE);
return 0; // the time will be sent later in response to serial mesg
}
推荐答案
Conrad 和我在 20 分钟聊天:
Conrad and I discovered the solution after a 20 minute chat:
To set the variable to EST
TZ_adjust=-5;
sudo echo "T$(($(date +%s)+60*60*$TZ_adjust))" >/dev/tty.usbmodemfa131
这篇关于无法通过 USB 将计算机时间同步到 Arduino的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!