PlatformIO package of the Teensy core framework compatible with GCC 10 & C++20
Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

82 lines
2.2KB

  1. /*
  2. * TimeSerial.pde
  3. * example code illustrating Time library set through serial port messages.
  4. *
  5. * Messages consist of the letter T followed by ten digit time (as seconds since Jan 1 1970)
  6. * you can send the text on the next line using Serial Monitor to set the clock to noon Jan 1 2013
  7. T1357041600
  8. *
  9. * A Processing example sketch to automatically send the messages is included in the download
  10. * On Linux, you can use "date +T%s\n > /dev/ttyACM0" (UTC time zone)
  11. */
  12. #include <TimeLib.h>
  13. #define TIME_HEADER "T" // Header tag for serial time sync message
  14. #define TIME_REQUEST 7 // ASCII bell character requests a time sync message
  15. void setup() {
  16. Serial.begin(9600);
  17. while (!Serial) ; // Needed for Leonardo only
  18. pinMode(13, OUTPUT);
  19. setSyncProvider( requestSync); //set function to call when sync required
  20. Serial.println("Waiting for sync message");
  21. }
  22. void loop(){
  23. if (Serial.available()) {
  24. processSyncMessage();
  25. }
  26. if (timeStatus()!= timeNotSet) {
  27. digitalClockDisplay();
  28. }
  29. if (timeStatus() == timeSet) {
  30. digitalWrite(13, HIGH); // LED on if synced
  31. } else {
  32. digitalWrite(13, LOW); // LED off if needs refresh
  33. }
  34. delay(1000);
  35. }
  36. void digitalClockDisplay(){
  37. // digital clock display of the time
  38. Serial.print(hour());
  39. printDigits(minute());
  40. printDigits(second());
  41. Serial.print(" ");
  42. Serial.print(day());
  43. Serial.print(" ");
  44. Serial.print(month());
  45. Serial.print(" ");
  46. Serial.print(year());
  47. Serial.println();
  48. }
  49. void printDigits(int digits){
  50. // utility function for digital clock display: prints preceding colon and leading 0
  51. Serial.print(":");
  52. if(digits < 10)
  53. Serial.print('0');
  54. Serial.print(digits);
  55. }
  56. void processSyncMessage() {
  57. unsigned long pctime;
  58. const unsigned long DEFAULT_TIME = 1357041600; // Jan 1 2013
  59. if(Serial.find(TIME_HEADER)) {
  60. pctime = Serial.parseInt();
  61. if( pctime >= DEFAULT_TIME) { // check the integer is a valid time (greater than Jan 1 2013)
  62. setTime(pctime); // Sync Arduino clock to the time received on the serial port
  63. }
  64. }
  65. }
  66. time_t requestSync()
  67. {
  68. Serial.write(TIME_REQUEST);
  69. return 0; // the time will be sent later in response to serial mesg
  70. }