PlatformIO package of the Teensy core framework compatible with GCC 10 & C++20
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

81 lines
2.0KB

  1. /*
  2. * TimeRTCSet.pde
  3. * example code illustrating Time library with Real Time Clock.
  4. *
  5. * RTC clock is set in response to serial port time message
  6. * A Processing example sketch to set the time is included in the download
  7. * On Linux, you can use "date +T%s > /dev/ttyACM0" (UTC time zone)
  8. */
  9. #include <TimeLib.h>
  10. #include <Wire.h>
  11. #include <DS1307RTC.h> // a basic DS1307 library that returns time as a time_t
  12. void setup() {
  13. Serial.begin(9600);
  14. while (!Serial) ; // Needed for Leonardo only
  15. setSyncProvider(RTC.get); // the function to get the time from the RTC
  16. if (timeStatus() != timeSet)
  17. Serial.println("Unable to sync with the RTC");
  18. else
  19. Serial.println("RTC has set the system time");
  20. }
  21. void loop()
  22. {
  23. if (Serial.available()) {
  24. time_t t = processSyncMessage();
  25. if (t != 0) {
  26. RTC.set(t); // set the RTC and the system time to the received value
  27. setTime(t);
  28. }
  29. }
  30. digitalClockDisplay();
  31. delay(1000);
  32. }
  33. void digitalClockDisplay(){
  34. // digital clock display of the time
  35. Serial.print(hour());
  36. printDigits(minute());
  37. printDigits(second());
  38. Serial.print(" ");
  39. Serial.print(day());
  40. Serial.print(" ");
  41. Serial.print(month());
  42. Serial.print(" ");
  43. Serial.print(year());
  44. Serial.println();
  45. }
  46. void printDigits(int digits){
  47. // utility function for digital clock display: prints preceding colon and leading 0
  48. Serial.print(":");
  49. if(digits < 10)
  50. Serial.print('0');
  51. Serial.print(digits);
  52. }
  53. /* code to process time sync messages from the serial port */
  54. #define TIME_HEADER "T" // Header tag for serial time sync message
  55. unsigned long processSyncMessage() {
  56. unsigned long pctime = 0L;
  57. const unsigned long DEFAULT_TIME = 1357041600; // Jan 1 2013
  58. if(Serial.find(TIME_HEADER)) {
  59. pctime = Serial.parseInt();
  60. return pctime;
  61. if( pctime < DEFAULT_TIME) { // check the value is a valid time (greater than Jan 1 2013)
  62. pctime = 0L; // return 0 to indicate that the time is not valid
  63. }
  64. }
  65. return pctime;
  66. }