Страница 1 из 4 1234 ПоследняяПоследняя
Показано с 1 по 10 из 35

Тема: Часы Arduino

  1. #1
    Новичок
    Регистрация
    26.10.2009
    Сообщений
    18
    Вес репутации
    182

    По умолчанию Часы Arduino

    Нужно програмно реализовать часы. Вариант либо тупо програмно все написать, либо прицепить DS1307 (как работать с ним не представляю). Задача сделать чтобы код занимал как можно меньше памяти ардуины. Задачу облегчает то обстоятельство, что переход на летнее-зимнее время с этого года не нужен.
    Спасибо всем кто откликнется и поможет с написанием скеча.

  2. #2
    Администратор Аватар для Chip
    Регистрация
    08.06.2007
    Возраст
    54
    Сообщений
    13,379
    Вес репутации
    10

    По умолчанию Re: Часы Arduino

    Программные часы написать не проблема , вот только нужно при этом обеспечить питание бесперебойное. Думаю что лучше на DS1307 реализовать.

  3. #3
    Пользователь
    Регистрация
    27.09.2009
    Возраст
    37
    Сообщений
    26
    Вес репутации
    191

    По умолчанию Re: Часы Arduino

    Полюбому лучше на ds1307, к ней подключается 3х вольтовая батарейка в качестве бесперебойного питания(кст. без нее часы не работают, просто внешего питания не хватает), общается он по протоколу i2c, отправляется адрес, запрос команды и считываются данные.

  4. #4
    Администратор Аватар для Chip
    Регистрация
    08.06.2007
    Возраст
    54
    Сообщений
    13,379
    Вес репутации
    10

    По умолчанию Re: Часы Arduino

    Вот готовый скетч для Carduino/Arduino
    PHP код:
    /*
     * RTC Control v.01
     * by <http://www.combustory.com> John Vaughters
     * Credit to:
     * Maurice Ribble - http://www.glacialwanderer.com/hobbyrobotics for RTC DS1307 code
     *
     * With this code you can set the date/time, retreive the date/time and use the extra memory of an RTC DS1307 chip.  
     * The program also sets all the extra memory space to 0xff.
     * Serial Communication method with the Arduino that utilizes a leading CHAR for each command described below. 
     * Commands:
     * T(00-59)(00-59)(00-23)(1-7)(01-31)(01-12)(00-99) - T(sec)(min)(hour)(dayOfWeek)(dayOfMonth)(month)(year) - T Sets the date of the RTC DS1307 Chip. 
     * Example to set the time for 02-Feb-09 @ 19:57:11 for the 3 day of the week, use this command - T1157193020209
     * Q(1-2) - (Q1) Memory initialization  (Q2) RTC - Memory Dump
     */

    #include "Wire.h"
    #define DS1307_I2C_ADDRESS 0x68  // This is the I2C address


    // Global Variables

    int command 0;       // This is the command char, in ascii form, sent from the serial port     
    int i;
    long previousMillis 0;        // will store last time Temp was updated
    byte secondminutehourdayOfWeekdayOfMonthmonthyear;
    byte test
      
    // Convert normal decimal numbers to binary coded decimal
    byte decToBcd(byte val)
    {
      return ( (
    val/10*16) + (val%10) );
    }

    // Convert binary coded decimal to normal decimal numbers
    byte bcdToDec(byte val)
    {
      return ( (
    val/16*10) + (val%16) );
    }

    // 1) Sets the date and time on the ds1307
    // 2) Starts the clock
    // 3) Sets hour mode to 24 hour clock
    // Assumes you're passing in valid numbers, Probably need to put in checks for valid numbers.
     
    void setDateDs1307()                
    {

       
    second = (byte) ((Serial.read() - 48) * 10 + (Serial.read() - 48)); // Use of (byte) type casting and ascii math to achieve result.  
       
    minute = (byte) ((Serial.read() - 48) *10 +  (Serial.read() - 48));
       
    hour  = (byte) ((Serial.read() - 48) *10 +  (Serial.read() - 48));
       
    dayOfWeek = (byte) (Serial.read() - 48);
       
    dayOfMonth = (byte) ((Serial.read() - 48) *10 +  (Serial.read() - 48));
       
    month = (byte) ((Serial.read() - 48) *10 +  (Serial.read() - 48));
       
    year= (byte) ((Serial.read() - 48) *10 +  (Serial.read() - 48));
       
    Wire.beginTransmission(DS1307_I2C_ADDRESS);
       
    Wire.send(0x00);
       
    Wire.send(decToBcd(second));    // 0 to bit 7 starts the clock
       
    Wire.send(decToBcd(minute));
       
    Wire.send(decToBcd(hour));      // If you want 12 hour am/pm you need to set
                                       // bit 6 (also need to change readDateDs1307)
       
    Wire.send(decToBcd(dayOfWeek));
       
    Wire.send(decToBcd(dayOfMonth));
       
    Wire.send(decToBcd(month));
       
    Wire.send(decToBcd(year));
       
    Wire.endTransmission();
    }

    // Gets the date and time from the ds1307 and prints result
    void getDateDs1307()
    {
      
    // Reset the register pointer
      
    Wire.beginTransmission(DS1307_I2C_ADDRESS);
      
    Wire.send(0x00);
      
    Wire.endTransmission();

      
    Wire.requestFrom(DS1307_I2C_ADDRESS7);

      
    // A few of these need masks because certain bits are control bits
      
    second     bcdToDec(Wire.receive() & 0x7f);
      
    minute     bcdToDec(Wire.receive());
      
    hour       bcdToDec(Wire.receive() & 0x3f);  // Need to change this if 12 hour am/pm
      
    dayOfWeek  bcdToDec(Wire.receive());
      
    dayOfMonth bcdToDec(Wire.receive());
      
    month      bcdToDec(Wire.receive());
      
    year       bcdToDec(Wire.receive());
      
      
    Serial.print(hourDEC);
      
    Serial.print(":");
      
    Serial.print(minuteDEC);
      
    Serial.print(":");
      
    Serial.print(secondDEC);
      
    Serial.print("  ");
      
    Serial.print(monthDEC);
      
    Serial.print("/");
      
    Serial.print(dayOfMonthDEC);
      
    Serial.print("/");
      
    Serial.print(yearDEC);

    }


    void setup() {
      
    Wire.begin();
      
    Serial.begin(57600);
     
    }

    void loop() {
         if (
    Serial.available()) {      // Look for char in serial que and process if found
          
    command Serial.read();
          if (
    command == 84) {      //If command = "T" Set Date
           
    setDateDs1307();
           
    getDateDs1307();
           
    Serial.println(" ");
          }
          else if (
    command == 81) {      //If command = "Q" RTC1307 Memory Functions
            
    delay(100);     
            if (
    Serial.available()) {
             
    command Serial.read(); 
             if (
    command == 49) {      //If command = "1" RTC1307 Initialize Memory - All Data will be set to 255 (0xff).  Therefore 255 or 0 will be an invalid value.  
              
    Wire.beginTransmission(DS1307_I2C_ADDRESS); // 255 will be the init value and 0 will be cosidered an error that occurs when the RTC is in Battery mode.
              
    Wire.send(0x08); // Set the register pointer to be just past the date/time registers.
             
    for (1<= 27i++) {
                 
    Wire.send(0xff);
                
    delay(100);
             }   
             
    Wire.endTransmission();
             
    getDateDs1307();
             
    Serial.println(": RTC1307 Initialized Memory");
             }
             else if (
    command == 50) {      //If command = "2" RTC1307 Memory Dump
              
    getDateDs1307();
              
    Serial.println(": RTC 1307 Dump Begin");
              
    Wire.beginTransmission(DS1307_I2C_ADDRESS);
              
    Wire.send(0x00);
              
    Wire.endTransmission();
              
    Wire.requestFrom(DS1307_I2C_ADDRESS64);
              for (
    1<= 64i++) {
                 
    test Wire.receive();
                 
    Serial.print(i);
                 
    Serial.print(":");
                 
    Serial.println(testDEC);
              }
              
    Serial.println(" RTC1307 Dump end");
             } 
            }  
           }
          
    Serial.print("Command: ");
          
    Serial.println(command);     // Echo command CHAR in ascii that was sent
          
    }
          
          
    command 0;                 // reset command 
          
    delay(100);
        } 

  5. #5
    Продвинутый Аватар для MiD_E34
    Регистрация
    11.01.2008
    Сообщений
    492
    Вес репутации
    300

    По умолчанию Re: Часы Arduino

    уже не помню точно, но для вычисления дня недели мне пришлось писать свою функцию - почему-то от 1307 не добился его.
    X-Trail,2010
    i5 Intel 3.5" board, DC-DC PS, 4G, W8.1x64, iCar, CityG.

  6. #6
    Новичок
    Регистрация
    26.10.2009
    Сообщений
    18
    Вес репутации
    182

    По умолчанию Re: Часы Arduino

    А как на счет схемы? куда чо подключать?

  7. #7
    Продвинутый Аватар для MiD_E34
    Регистрация
    11.01.2008
    Сообщений
    492
    Вес репутации
    300

    По умолчанию Re: Часы Arduino

    Цитата Сообщение от Ger$$$ Посмотреть сообщение
    А как на счет схемы? куда чо подключать?
    ну так... нетрудно составить - 2 порта возьмет шина ДС1307, сколько-то дисплей (не помню сколько он берет линий) и кнопки. Думаю хватит трех кнопок - перемещиние по меню "по кругу" и "+","-" - чтобы время задать. Я 1307 делал отдельным модулем с батарейкой на маленькой плате - втыкай куда хочешь.
    В Протеусе быстро получится - там есть уже база элементов.
    X-Trail,2010
    i5 Intel 3.5" board, DC-DC PS, 4G, W8.1x64, iCar, CityG.

  8. #8
    Новичок
    Регистрация
    26.10.2009
    Сообщений
    18
    Вес репутации
    182

    По умолчанию Re: Часы Arduino

    я про то как дс-ку подключить к ардуине, и патанию? из скеча не догнал что куда идет...

  9. #9
    Новичок
    Регистрация
    14.01.2010
    Сообщений
    9
    Вес репутации
    177

    По умолчанию Re: Часы Arduino

    http://www.glacialwanderer.com/hobbyrobotics/?p=12



    смотри описание DS-ки, там есть входы для доп. питания.
    Последний раз редактировалось nevsky; 18.03.2010 в 14:40.

  10. #10
    Новичок
    Регистрация
    31.05.2010
    Возраст
    39
    Сообщений
    1
    Вес репутации
    0

    По умолчанию Re: Часы Arduino

    Nice для чтения этого я должен сказать, очень полезный и информативный еще один интересный

Страница 1 из 4 1234 ПоследняяПоследняя

Информация о теме

Пользователи, просматривающие эту тему

Эту тему просматривают: 1 (пользователей: 0 , гостей: 1)

Ваши права

  • Вы не можете создавать новые темы
  • Вы не можете отвечать в темах
  • Вы не можете прикреплять вложения
  • Вы не можете редактировать свои сообщения
  •