Operácie

Zbernica i2c: RTC Hodiny

Zo stránky SensorWiki

Záverečný projekt predmetu MIPS / LS2026 - Andrej Koža


Zadanie

Cieľom projektu je pomocou I2C zbernice vyčítať reálny čas z RTC modulu DS1307 a zobraziť ho na sériovom terminály cez UART. Modul DS1307 obsahuje hodiny a kalendár s vlastnou zálohovacou batériou, takže si čas uchová aj po odpojení napájania. Program každú sekundu prečíta aktuálny čas a dátum a vypíše ich vo formáte DD.MM.RRRR (Deň) HH:MM:SS.


Časový modul s DS1307

Literatúra:


Analýza a opis riešenia

Projekt využíva mikrokontrolér ATmega328P a externý RTC modul DS1307 zapojený cez I2C zbernicu. Komunikácia prebieha po dvoch vodičoch – SDA (dátová linka) a SCL (hodinová linka), pričom ATmega328P vystupuje ako master a DS1307 ako slave zariadenie s pevnou adresou 0x68.

Na obsluhu I2C zbernice je použitá knižnica Peter Fleury I2C Master Library (i2cmaster.h + i2cmaster.c), ktorá využíva hardvérový TWI modul ATmega328P.

Piny SDA a SCL sú pevne dané výrobcom čipu – PC4 (A4) pre SDA a PC5 (A5) pre SCL, nie je možné ich zmeniť na iné piny. Na oboch linkách sú nutné pull-up rezistory 4,7 kΩ na +5V. Na použitom DS1307 module sú tieto odpory už osadené priamo na doske.

DS1307 ukladá všetky hodnoty (sekundy, minúty, hodiny, dátum, mesiac, rok) v BCD formáte (Binary Coded Decimal), kde každá decimálna cifra je zakódovaná do samostatného 4-bitového nibble. Napríklad číslo 47 je uložené ako 0x47 (nie ako 0x2F čo by bol bežný hex zápis). Preto je v kóde nutná konverzia pomocou funkcií bcd_to_dec() a dec_to_bcd() pri každom čítaní a zápise.

uint8_t bcd_to_dec(uint8_t bcd)
{
    return ((bcd >> 4) * 10) + (bcd & 0x0F);
}

uint8_t dec_to_bcd(uint8_t dec)
{
    return ((dec / 10) << 4) | (dec % 10);
}

Dôležitý detail: bit CH (Clock Halt) v bite 7 registra sekúnd musí byť 0, inak DS1307 hodiny netíkajú. Továrensky je tento bit nastavený na 1 (hodiny zastavené), preto ho pri zápise vždy vynulujeme operáciou & 0x7F.


Schéma zapojenia


Schéma zapojenia.


Algoritmus a program

Program po inicializácii UART a I2C jednorazovo zapíše aktuálny čas do DS1307 (po prvom nahraní sa tento riadok zakomentuje). Následne v nekonečnej slučke každú sekundu vyčíta 7 registrov DS1307 cez I2C a vypíše ich na UART. Čítanie prebieha v dvoch fázach:

1. Zápisom adresy 0x00 nastavíme register pointer DS1307 na začiatok (sekundy)

2. Sekvenčným čítaním 7 bajtov získame sekundy, minúty, hodiny, deň, dátum, mesiac a rok – DS1307 automaticky inkrementuje adresu po každom bajte. Posledný bajt ukončíme signálom NACK (i2c_readNak), predchádzajúce ACK (i2c_readAck).



/*
 * MipsProjekt.c
 *
 *  Projekt:  Zbernica I2C – RTC Hodiny (DS1307)
 *  Popis:    Vyčítanie reálneho času a dátumu z RTC modulu DS1307
 *            cez I2C zbernicu a výpis na UART (sériový terminál).
 *
 *  Zapojenie (ATmega328P):
 *    DS1307 SDA  ->  PC4 (SDA)  + pull-up 4,7k Ohm na +5V
 *    DS1307 SCL  ->  PC5 (SCL)  + pull-up 4,7k Ohm na +5V
 *    DS1307 VCC  ->  +5V
 *    DS1307 GND  ->  GND
 *
 *  Knižnice:
 *    uart.h      – zo cvičení (UART komunikácia)
 *	  uart.c
 *    i2cmaster.h – zo cvičení I2C komunikácia (Peter Fleury) 
 *    i2cmaster.c – 
 */

#define F_CPU 16000000UL
#define BAUD  9600
#define BAUD_PRESCALE (((F_CPU / (BAUD * 16UL))) - 1)

#include <util/delay.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdio.h>
#include "uart.h"
#include "i2cmaster.h"   // Fleuryho I2C knižnica

#define set_bit(ADDRESS,BIT)   (ADDRESS |=  (1<<BIT))
#define clear_bit(ADDRESS,BIT) (ADDRESS &= ~(1<<BIT))

FILE uart_output = FDEV_SETUP_STREAM(uart_putc, NULL, _FDEV_SETUP_WRITE);
FILE uart_input  = FDEV_SETUP_STREAM(NULL, uart_getc, _FDEV_SETUP_READ);

/* 
   Konštanty pre DS1307
   
   Fleuryho knižnica očakáva adresu vo formáte: (7bit_adresa << 1) | smer
   DS1307 má 7-bitovú adresu 0x68.
   I2C_WRITE = 0, I2C_READ = 1  (definované v i2cmaster.h)
*/
#define DS1307_W  (0x68 << 1 | I2C_WRITE)   // = 0xD0
#define DS1307_R  (0x68 << 1 | I2C_READ)    // = 0xD1

// Adresy registrov DS1307 (hodnoty sú v BCD formáte)
#define REG_SEC   0x00   // Sekundy  (00-59)
#define REG_MIN   0x01   // Minúty   (00-59)
#define REG_HOUR  0x02   // Hodiny   (00-23 v 24h režime)
#define REG_DAY   0x03   // Deň týždňa (1-7)
#define REG_DATE  0x04   // Dátum    (01-31)
#define REG_MON   0x05   // Mesiac   (01-12)
#define REG_YEAR  0x06   // Rok      (00-99)

/* 
   BCD konverzia
   DS1307 ukladá čísla v BCD (Binary Coded Decimal) formáte.
   Príklad: decimálne 47 je v BCD uložené ako 0x47 = 0100 0111
            horný nibble = 4 (desiatky), dolný nibble = 7 (jednotky)
*/
uint8_t bcd_to_dec(uint8_t bcd)
{
    return ((bcd >> 4) * 10) + (bcd & 0x0F);
}

uint8_t dec_to_bcd(uint8_t dec)
{
    return ((dec / 10) << 4) | (dec % 10);
}

/* 
   Štruktúra pre uloženie času a dátumu
*/
typedef struct {
    uint8_t sekunda;     // 0-59
    uint8_t minuta;      // 0-59
    uint8_t hodina;      // 0-23
    uint8_t den_tyzdna;  // 1-7
    uint8_t datum;       // 1-31
    uint8_t mesiac;      // 1-12
    uint8_t rok;         // 0-99 (napr. 26 = 2026)
} RTC_Cas;

/* 
   ds1307_set_time – zápis času do DS1307
   Používa Fleuryho i2c_start_wait() – ak je DS1307 zaneprázdnený,
   funkcia čaká kým sa neuvoľní.
*/
void ds1307_set_time(RTC_Cas *cas)
{
    i2c_start_wait(DS1307_W);      // Čakáme na DS1307, nastavíme zápis
    i2c_write(REG_SEC);            // Register pointer -> 0x00 (sekundy)

    // Bit CH (bit 7 reg. sekúnd) nastavíme na 0 -> hodiny BEŽIA
    // Továrenske nastavenie DS1307 má CH=1 (hodiny zastavené)!
    i2c_write(dec_to_bcd(cas->sekunda) & 0x7F);   // Sekundy + CH=0
    i2c_write(dec_to_bcd(cas->minuta));           // Minúty
    i2c_write(dec_to_bcd(cas->hodina)  & 0x3F);   // Hodiny (24h, bit6=0)
    i2c_write(dec_to_bcd(cas->den_tyzdna));         // Deň týždňa
    i2c_write(dec_to_bcd(cas->datum));              // Dátum
    i2c_write(dec_to_bcd(cas->mesiac));             // Mesiac
    i2c_write(dec_to_bcd(cas->rok));                // Rok (napr. 26 == 2026)
    i2c_stop();                    // Uvoľníme zbernicu
}

/* 
   ds1307_get_time – čítanie času z DS1307
   DS1307 po nastavení register pointera automaticky
   inkrementuje adresu po každom prečítanom bajte.
*/
void ds1307_get_time(RTC_Cas *cas)
{
    // Krok 1: Zápisom nastavíme register pointer na 0x00 (sekundy)
    i2c_start_wait(DS1307_W);   // Adresa DS1307, zápis
    i2c_write(REG_SEC);         // Register pointer na 0x00
    i2c_stop();

    // Krok 2: start + čítanie 7 registrov za sebou
    i2c_start_wait(DS1307_R);   // Adresa DS1307, čítanie

    // i2c_readAck()  = prečítaj bajt a pošli ACK (chceme ďalší bajt)
    // i2c_readNak()  = prečítaj bajt a pošli NACK (posledný bajt)
    cas->sekunda    = bcd_to_dec(i2c_readAck()  & 0x7F); //  CH bit
    cas->minuta     = bcd_to_dec(i2c_readAck());
    cas->hodina     = bcd_to_dec(i2c_readAck()  & 0x3F); //  12/24h bit
    cas->den_tyzdna = bcd_to_dec(i2c_readAck());
    cas->datum      = bcd_to_dec(i2c_readAck());
    cas->mesiac     = bcd_to_dec(i2c_readAck());
    cas->rok        = bcd_to_dec(i2c_readNak());          // posledný -> NACK

    i2c_stop();
}

/* 
   nazov_dna – textový názov dňa (1=Pondelok ... 7=Nedela)
*/
const char* nazov_dna(uint8_t den)
{
    switch(den) {
        case 1: return "Pondelok";
        case 2: return "Utorok";
        case 3: return "Streda";
        case 4: return "Stvrtok";
        case 5: return "Piatok";
        case 6: return "Sobota";
        case 7: return "Nedela";
        default: return "???";
    }
}

void delay_ms(int ms)
{
    for (int i = 0; i < ms; i++)
        _delay_ms(1);
}


/* 
   HLAVNÝ PROGRAM
*/
int main(void)
{
    stdout = &uart_output;
    stdin  = &uart_input;

    uart_init();   // Inicializácia UART (9600 baud)
    i2c_init();    // Inicializácia I2C – Fleuryho funkcia (i2cmaster.c)

    
/*  NASTAVENIE ČASU – treba zakomentovať po prvom nahrani, inak sa čas resetuje
   pri každom reštarte mikropočítača.
*/    
    RTC_Cas nastavenie = {
        .sekunda    = 0,
        .minuta     = 48,
        .hodina     = 17,
        .den_tyzdna = 2,    // 2 = Utorok
        .datum      = 12,
        .mesiac     = 5,
        .rok        = 26    // 2026
    };
    ds1307_set_time(&nastavenie);

    printf("=== RTC Hodiny DS1307 cez I2C ===\r\n");
    printf("Format: DD.MM.20RR (Den) HH:MM:SS\r\n");
    printf("----------------------------------\r\n");

    RTC_Cas cas;

    while(1)
    {
        ds1307_get_time(&cas);

        printf("%02u.%02u.20%02u (%s) %02u:%02u:%02u\r\n",
               cas.datum,
               cas.mesiac,
               cas.rok,
               nazov_dna(cas.den_tyzdna),
               cas.hodina,
               cas.minuta,
               cas.sekunda);

        delay_ms(1000);
    }
}
#ifndef UART_H_
#define UART_H_

void uart_init( void );
     
void uart_putc( char c );
void uart_puts( const char *s );

char uart_getc( void );



#endif
#define F_CPU 16000000
#define BAUD       9600

#include <avr/io.h>
#include "uart.h"
#include <util/setbaud.h>

void uart_init( void ) 
{
    UBRR0H = UBRRH_VALUE;
    UBRR0L = UBRRL_VALUE;

#if USE_2X
    UCSR0A |= _BV(U2X0);
#else
    UCSR0A &= ~(_BV(U2X0));
#endif

    UCSR0C = _BV(UCSZ01) | _BV(UCSZ00); /* 8-bit data */
    UCSR0B = _BV(RXEN0) | _BV(TXEN0);   /* Enable RX and TX */
}


void uart_putc(char c) 
{
   if (c == '\n') 
    {
       uart_putc('\r');
    }
   loop_until_bit_is_set(UCSR0A, UDRE0); /* Wait until data register empty. */
   UDR0 = c;
}


void uart_puts(const char *s)
{
  /* toto je vasa uloha */
}

char uart_getc(void) {
    loop_until_bit_is_set(UCSR0A, RXC0); /* Wait until data exists. */
    return UDR0;
}
#ifndef _I2CMASTER_H
#define _I2CMASTER_H
/************************************************************************* 
* Title:    C include file for the I2C master interface 
*           (i2cmaster.S or twimaster.c)
* Author:   Peter Fleury <pfleury@gmx.ch>
* File:     $Id: i2cmaster.h,v 1.12 2015/09/16 09:27:58 peter Exp $
* Software: AVR-GCC 4.x
* Target:   any AVR device
* Usage:    see Doxygen manual
**************************************************************************/

/**
 @file
 @defgroup pfleury_ic2master I2C Master library
 @code #include <i2cmaster.h> @endcode
  
 @brief I2C (TWI) Master Software Library

 Basic routines for communicating with I2C slave devices. This single master 
 implementation is limited to one bus master on the I2C bus. 

 This I2c library is implemented as a compact assembler software implementation of the I2C protocol 
 which runs on any AVR (i2cmaster.S) and as a TWI hardware interface for all AVR with built-in TWI hardware (twimaster.c).
 Since the API for these two implementations is exactly the same, an application can be linked either against the
 software I2C implementation or the hardware I2C implementation.

 Use 4.7k pull-up resistor on the SDA and SCL pin.
 
 Adapt the SCL and SDA port and pin definitions and eventually the delay routine in the module 
 i2cmaster.S to your target when using the software I2C implementation ! 
 
 Adjust the  CPU clock frequence F_CPU in twimaster.c or in the Makfile when using the TWI hardware implementaion.

 @note 
    The module i2cmaster.S is based on the Atmel Application Note AVR300, corrected and adapted 
    to GNU assembler and AVR-GCC C call interface.
    Replaced the incorrect quarter period delays found in AVR300 with 
    half period delays. 
    
 @author Peter Fleury pfleury@gmx.ch  http://tinyurl.com/peterfleury
 @copyright (C) 2015 Peter Fleury, GNU General Public License Version 3
 
 @par API Usage Example
  The following code shows typical usage of this library, see example test_i2cmaster.c

 @code

 #include <i2cmaster.h>


 #define Dev24C02  0xA2      // device address of EEPROM 24C02, see datasheet

 int main(void)
 {
     unsigned char ret;

     i2c_init();                             // initialize I2C library

     // write 0x75 to EEPROM address 5 (Byte Write) 
     i2c_start_wait(Dev24C02+I2C_WRITE);     // set device address and write mode
     i2c_write(0x05);                        // write address = 5
     i2c_write(0x75);                        // write value 0x75 to EEPROM
     i2c_stop();                             // set stop conditon = release bus


     // read previously written value back from EEPROM address 5 
     i2c_start_wait(Dev24C02+I2C_WRITE);     // set device address and write mode

     i2c_write(0x05);                        // write address = 5
     i2c_rep_start(Dev24C02+I2C_READ);       // set device address and read mode

     ret = i2c_readNak();                    // read one byte from EEPROM
     i2c_stop();

     for(;;);
 }
 @endcode

*/


/**@{*/

#if (__GNUC__ * 100 + __GNUC_MINOR__) < 304
#error "This library requires AVR-GCC 3.4 or later, update to newer AVR-GCC compiler !"
#endif

#include <avr/io.h>

/** defines the data direction (reading from I2C device) in i2c_start(),i2c_rep_start() */
#define I2C_READ    1

/** defines the data direction (writing to I2C device) in i2c_start(),i2c_rep_start() */
#define I2C_WRITE   0


/**
 @brief initialize the I2C master interace. Need to be called only once 
 @return none
 */
extern void i2c_init(void);


/** 
 @brief Terminates the data transfer and releases the I2C bus 
 @return none
 */
extern void i2c_stop(void);


/** 
 @brief Issues a start condition and sends address and transfer direction 
  
 @param    addr address and transfer direction of I2C device
 @retval   0   device accessible 
 @retval   1   failed to access device 
 */
extern unsigned char i2c_start(unsigned char addr);


/**
 @brief Issues a repeated start condition and sends address and transfer direction 

 @param   addr address and transfer direction of I2C device
 @retval  0 device accessible
 @retval  1 failed to access device
 */
extern unsigned char i2c_rep_start(unsigned char addr);


/**
 @brief Issues a start condition and sends address and transfer direction 
   
 If device is busy, use ack polling to wait until device ready 
 @param    addr address and transfer direction of I2C device
 @return   none
 */
extern void i2c_start_wait(unsigned char addr);

 
/**
 @brief Send one byte to I2C device
 @param    data  byte to be transfered
 @retval   0 write successful
 @retval   1 write failed
 */
extern unsigned char i2c_write(unsigned char data);


/**
 @brief    read one byte from the I2C device, request more data from device 
 @return   byte read from I2C device
 */
extern unsigned char i2c_readAck(void);

/**
 @brief    read one byte from the I2C device, read is followed by a stop condition 
 @return   byte read from I2C device
 */
extern unsigned char i2c_readNak(void);

/** 
 @brief    read one byte from the I2C device
 
 Implemented as a macro, which calls either @ref i2c_readAck or @ref i2c_readNak
 
 @param    ack 1 send ack, request more data from device<br>
               0 send nak, read is followed by a stop condition 
 @return   byte read from I2C device
 */
extern unsigned char i2c_read(unsigned char ack);
#define i2c_read(ack)  (ack) ? i2c_readAck() : i2c_readNak(); 



/**@}*/
#endif
/*************************************************************************
* Title:    I2C master library using hardware TWI interface
* Author:   Peter Fleury <pfleury@gmx.ch>  http://jump.to/fleury
* File:     $Id: twimaster.c,v 1.4 2015/01/17 12:16:05 peter Exp $
* Software: AVR-GCC 3.4.3 / avr-libc 1.2.3
* Target:   any AVR device with hardware TWI 
* Usage:    API compatible with I2C Software Library i2cmaster.h
**************************************************************************/
#include <inttypes.h>
#include <compat/twi.h>

#include "i2cmaster.h"


/* define CPU frequency in hz here if not defined in Makefile */
#ifndef F_CPU
#define F_CPU 16000000UL
#endif

/* I2C clock in Hz */
#define SCL_CLOCK  100000L


/*************************************************************************
 Initialization of the I2C bus interface. Need to be called only once
*************************************************************************/
void i2c_init(void)
{
  /* initialize TWI clock: 100 kHz clock, TWPS = 0 => prescaler = 1 */
  
  TWSR = 0;                         /* no prescaler */
  TWBR = ((F_CPU/SCL_CLOCK)-16)/2;  /* must be > 10 for stable operation */

}/* i2c_init */


/*************************************************************************	
  Issues a start condition and sends address and transfer direction.
  return 0 = device accessible, 1= failed to access device
*************************************************************************/
unsigned char i2c_start(unsigned char address)
{
    uint8_t   twst;

	// send START condition
	TWCR = (1<<TWINT) | (1<<TWSTA) | (1<<TWEN);

	// wait until transmission completed
	while(!(TWCR & (1<<TWINT)));

	// check value of TWI Status Register. Mask prescaler bits.
	twst = TW_STATUS & 0xF8;
	if ( (twst != TW_START) && (twst != TW_REP_START)) return 1;

	// send device address
	TWDR = address;
	TWCR = (1<<TWINT) | (1<<TWEN);

	// wail until transmission completed and ACK/NACK has been received
	while(!(TWCR & (1<<TWINT)));

	// check value of TWI Status Register. Mask prescaler bits.
	twst = TW_STATUS & 0xF8;
	if ( (twst != TW_MT_SLA_ACK) && (twst != TW_MR_SLA_ACK) ) return 1;

	return 0;

}/* i2c_start */


/*************************************************************************
 Issues a start condition and sends address and transfer direction.
 If device is busy, use ack polling to wait until device is ready
 
 Input:   address and transfer direction of I2C device
*************************************************************************/
void i2c_start_wait(unsigned char address)
{
    uint8_t   twst;


    while ( 1 )
    {
	    // send START condition
	    TWCR = (1<<TWINT) | (1<<TWSTA) | (1<<TWEN);
    
    	// wait until transmission completed
    	while(!(TWCR & (1<<TWINT)));
    
    	// check value of TWI Status Register. Mask prescaler bits.
    	twst = TW_STATUS & 0xF8;
    	if ( (twst != TW_START) && (twst != TW_REP_START)) continue;
    
    	// send device address
    	TWDR = address;
    	TWCR = (1<<TWINT) | (1<<TWEN);
    
    	// wail until transmission completed
    	while(!(TWCR & (1<<TWINT)));
    
    	// check value of TWI Status Register. Mask prescaler bits.
    	twst = TW_STATUS & 0xF8;
    	if ( (twst == TW_MT_SLA_NACK )||(twst ==TW_MR_DATA_NACK) ) 
    	{    	    
    	    /* device busy, send stop condition to terminate write operation */
	        TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO);
	        
	        // wait until stop condition is executed and bus released
	        while(TWCR & (1<<TWSTO));
	        
    	    continue;
    	}
    	//if( twst != TW_MT_SLA_ACK) return 1;
    	break;
     }

}/* i2c_start_wait */


/*************************************************************************
 Issues a repeated start condition and sends address and transfer direction 

 Input:   address and transfer direction of I2C device
 
 Return:  0 device accessible
          1 failed to access device
*************************************************************************/
unsigned char i2c_rep_start(unsigned char address)
{
    return i2c_start( address );

}/* i2c_rep_start */


/*************************************************************************
 Terminates the data transfer and releases the I2C bus
*************************************************************************/
void i2c_stop(void)
{
    /* send stop condition */
	TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO);
	
	// wait until stop condition is executed and bus released
	while(TWCR & (1<<TWSTO));

}/* i2c_stop */


/*************************************************************************
  Send one byte to I2C device
  
  Input:    byte to be transfered
  Return:   0 write successful 
            1 write failed
*************************************************************************/
unsigned char i2c_write( unsigned char data )
{	
    uint8_t   twst;
    
	// send data to the previously addressed device
	TWDR = data;
	TWCR = (1<<TWINT) | (1<<TWEN);

	// wait until transmission completed
	while(!(TWCR & (1<<TWINT)));

	// check value of TWI Status Register. Mask prescaler bits
	twst = TW_STATUS & 0xF8;
	if( twst != TW_MT_DATA_ACK) return 1;
	return 0;

}/* i2c_write */


/*************************************************************************
 Read one byte from the I2C device, request more data from device 
 
 Return:  byte read from I2C device
*************************************************************************/
unsigned char i2c_readAck(void)
{
	TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWEA);
	while(!(TWCR & (1<<TWINT)));    

    return TWDR;

}/* i2c_readAck */


/*************************************************************************
 Read one byte from the I2C device, read is followed by a stop condition 
 
 Return:  byte read from I2C device
*************************************************************************/
unsigned char i2c_readNak(void)
{
	TWCR = (1<<TWINT) | (1<<TWEN);
	while(!(TWCR & (1<<TWINT)));
	
    return TWDR;

}/* i2c_readNak */

Pridajte sem aj zbalený kompletný projekt, napríklad takto (použite jednoznačné pomenovanie, nemôžeme mať na serveri 10x zdrojaky.zip:

Zdrojový kód: zdrojaky.zip

Overenie

Program bol odskúšaný na doske s ATmega328P pripojenej k DS1307 modulu. Po nahraní programu a otvorení sériového terminálu (PuTTY, 9600 baud) sa každú sekundu zobrazoval aktuálny čas a dátum. Po odpojení a opätovnom pripojení napájania modul správne pokračoval v odčítavaní času bez nutnosti opätovného nastavenia, čo potvrdilo správnu funkciu zálohovacej batérie CR2032.


Aplikácia.

Video:

Čo by som urobil inak

Zamyslite sa spätne nad problémom, ktorý ste riešili a napíšte, čo sa vám nepodarilo a nabudúce by ste spravili inak.


Kľúčové slová 'Category', ktoré sú na konci stránky nemeňte.