• 1

    ..

  • 2

    ...

  • 3

    ...

Sunday, 16 February 2014

DS1307 SERIAL RTC (Real Time Clock) - AVR INTERFACING HEADER FILE - FUNCTION CODES


        The DS1307 serial real-time clock (RTC) is a low power, full binary-coded decimal (BCD) clock/calendar plus 56 bytes of NV SRAM. Address and data are transferred serially through an I2C, bidirectional bus. The clock/calendar provides seconds, minutes, hours, day, date, month, and year information. The end of the month date is automatically adjusted for months with fewer than 31 days, including corrections for leap year. The clock operates in either the 24-hour or 12- hour format with AM/PM indicator.

        The DS1307 has a built-in power-sense circuit that detects power failures and automatically switches to the backup supply. Timekeeping operation continues while the part operates from the backup supply. The DS1307 operates as a slave device on the I2C bus. Access is obtained by implementing a START condition and providing a device identification code followed by a register address. Subsequent registers can be accessed sequentially until a STOP condition is executed.

        When VCC falls below 1.25 x VBAT, the device terminates an access in progress and resets the device address counter. Inputs to the device will not be recognized at this time to prevent erroneous data from being written to the device from an out-of-tolerance system. When VCC falls below VBAT, the device switches into a low-current battery-backup mode. Upon power-up, the device switches from battery to VCC when VCC is greater than VBAT +0.2V and recognizes inputs when VCC is greater than 1.25 x VBAT.


FEATURES
·         Real-Time Clock (RTC) Counts Seconds, Minutes, Hours, Date of the Month, Month, Day of the week, and Year with Leap-Year Compensation
·         56-Byte, Battery-Backed, General-Purpose RAM with Unlimited Writes
·         I2C Serial Interface
·         Programmable Square-Wave Output Signal
·         Automatic Power-Fail Detect and Switch Circuitry
·         Consumes Less than 500nA in Battery-Backup Mode with Oscillator Running
·         Optional Industrial Temperature Range: -40°C to +85°C
·         Available in 8-Pin Plastic DIP or SO

Interfacing Circuit Diagram:



FUNCTIONS OF I2C.H
    void I2CInit();
    void I2CStart();
    void I2CStop();
    unsigned char I2CWriteSLA(unsigned char sla);
    unsigned char I2CWriteByte(unsigned char dat);
    unsigned char I2CReadByte(unsigned char *data);

FUNCTIONS IN DS1307.H
    DSinit();
        To initialise DS1307 RTC chip

    DSReadTime(&h, &m, &s)
        To read time hr, min, sec from RTC

    DSReadDate(&d, &m, &y)
        To read date from RTC
   
    DSReadDay(&dy)
        To read day from RTC

    DSWriteDay(dy)
        To write day to RTC


REGISTER MAP OF DS1307 RTC

  NOTE:
              CH is Clock Halt bit,  OSC disabled if CH=1
               12/24~ =1 -> 12 hour mode, bit5 0=AM  1=PM
                            =0 -> 24 hour mode, bit5 10hour

Control Register:
Bit 7: Output Control (OUT). This bit controls the output level of the SQW/OUT pin when the square-wave output
is disabled. If SQWE = 0, the logic level on the SQW/OUT pin is 1 if OUT = 1 and is 0 if OUT = 0. On initial
application of power to the device, this bit is typically set to a 0.

Bit 4: Square-Wave Enable (SQWE). This bit, when set to logic 1, enables the oscillator output. The frequency of
the square-wave output depends upon the value of the RS0 and RS1 bits. With the square-wave output set to 1Hz,
the clock registers update on the falling edge of the square wave. On initial application of power to the device, this
bit is typically set to a 0.

Bits 1 and 0: Rate Select (RS[1:0]). These bits control the frequency of the square-wave output when the squarewave
output has been enabled. It can be set to 1Hz, 4.096KHz, 8.192KHz or 32.768KHz On initial application of power to
the device, these bits are typically set to a 1.

/*
THIS WORK IS INTENDED TO BE USED FOR HOBBY & LEARNING PURPOSE ONLY. NO PART OF THIS CAN BE PUBLISHED OR USED IN COMMERCIAL PRODUCTS WITHOUT A WRITTEN PERMISSION FROM ELECDUDE.

#ifndef _ds1307_H

#define _ds1307_H
#include <util/twi.h>

#ifndef BIT
#define BIT(x)    _BV(x)

Thursday, 13 February 2014

INTERFACING SWITCH WITH AVR MICROCONTROLLER WITH INTERRUPT

           Switches are used to do intended actions or a task when pressed. This is most common in embedded devices. But polling a key press can cause more code to repeat until a valid key is recognized & power will be wasted.

           One solution is to use the keys with interrupt. So the ISR will be made to do the task of the key. In the main loop this task is removed so the MCU can be put into sleep mode, where an interrupt will make MCU to wake up. Here we present a simple code with 3 switches connected to interrupt the CPU when pressed. Note that Sleep mode is not used in this project, but it is simple to add.

CLICK HERE TO VIEW SLEEP MODE EXAMPLE.


         In this example we have used AVR Atmega8 microcontroller, the keypress ISR determines which key is pressed & displays it in USART. Note that the ISR returns only when the pressed is released. This is added for proper key de-bounce action, but much longer key press can cause lock-up until it is released. So triple check the circuit connections for errors & short circuits before powering up. This is optional & can be removed.

Circuit Diagram:

Program:
THIS WORK IS INTENDED TO BE USED FOR HOBBY & LEARNING PURPOSE ONLY. NO PART OF THIS CAN BE PUBLISHED OR USED IN COMMERCIAL PRODUCTS WITHOUT A WRITTEN PERMISSION FROM ELECDUDE.

#define F_CPU 1000000UL

#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

/*****************MACRO's DEFINITION*********************************/
#define BIT(x)        (1 << (x))    //Set a particular bit mask
#define CHECKBIT(x,b)     (x & BIT(b))    //Checks bit status
#define SETBIT(x,b)     x|=BIT(b);    //Sets the particular bit
#define CLEARBIT(x,b)     x&=~BIT(b);    //Sets the particular bit
#define TOGGLEBIT(x,b)     x^=BIT(b);    //Toggles the particular bit
unsigned char ch='A';
#include "USART.h"

//ISR_ALIAS(INT1_vect, INT0_vect);//1->0
ISR(INT0_vect)
{
    ch=PINC; //read key status
    while(bit_is_clear(PIND,2)); //wait for de-bounce
    ch=((~ch) & 0x07);
    uart_puts_p("Switch ");
    switch(ch)
     {
      case 1:uart_putc('1');break;
      case 2:uart_putc('2');break;
      case 4:uart_putc('3');break;
     }
    uart_puts_p(" is pressed\n\r");
}

int main()
{
    PORTD=0xFF;//enable pull ups @ PD
            //int1 posedge        int0 posedge
    MCUCR|=(0<<ISC11)
|(0<<ISC10)|(1<<ISC01)|(0<<ISC00);
    GICR |= (0<<INT1)|(1<<INT0);//enable INT1 & INT0

    DDRD=0x00;//for i/P
   
    DDRB=0xFF;
    DDRC=0xF0;
    PORTC=0x0F;
   
    uart_init(9600,2);
    _delay_ms(50);
    uart_puts_p("Welcome...\n\r");
    sei();

     while(1)
         {
        //
        //
        }
 return 0;
}

// waits (pauses) for ms milliseconds
void WaitMs(unsigned int ms)
{
    unsigned int m;

    for(m=0;m<=ms/10;m++)
    {
        _delay_ms(10);
    }
}
Click here to goto USART example download.

Proteus Simulation Output Snapshot:






If you enjoyed this post plz let us know your views via comments.
This helps us to do much more better.
Thankyou.

Monday, 10 February 2014

PERIODIC, APERIODIC, PULSE TRAIN WAVEFORMS IN MATLAB – EXAMPLE CODE


       This example show s how to generate widely used periodic and aperiodic waveforms, sequences (impulse, step, ramp), pulse trains in Matlab.


Periodic Waveforms:
In addition to the sin and cos functions in MATLAB, we can produce periodic signals such as saw tooth and square.

The saw tooth function generates a saw tooth wave with peaks at +/- 1 and a period of 2*pi.  The fractional multiple of '2*pi' specifies the point at which the signal's maximum occurs.

The square function generates a square wave with a period of 2*pi.  The duty cycle can also be adjusted.

fs = 10000; %sampling freq
t = 0:1/fs:1.5; % 0s to 1.5s with Fs sample freq
x1 = sawtooth(2*pi*50*t);  % 2*pi* freq * time duration
x2 = square(2*pi*50*t);
subplot(211),plot(t,x1), axis([0 0.2 -1.2 1.2])
xlabel('Time (sec)');ylabel('Amplitude'); title('Sawtooth Periodic Wave')
subplot(212),plot(t,x2), axis([0 0.2 -1.2 1.2])
xlabel('Time (sec)');ylabel('Amplitude'); title('Square Periodic Wave')


Aperiodic Waveforms:
To generate triangular, rectangular and Gaussian pulses, the toolbox offers the tripuls,  rectpuls and gauspuls functions.

The tripuls function generates a sampled aperiodic, unity-height triangular pulse centered about t = 0 and with a default width of 1.
       tripuls(t,wid); t= time duration, wid=pulse width

The rectpuls function generates a sampled aperiodic, unity-height rectangular pulse centered about t = 0 and with a default width of 1. The interval of non-zero amplitude is defined to be open on the right, that is, rectpuls(-0.5) = 1 while rectpuls(0.5) = 0.
       rectpuls(t,wid); t= time duration, wid=pulse width

fs = 10000; %sampling freq
t = -1:1/fs:1; % -1s to +1s with Fs sample freq
x1 = tripuls(t,20e-3);
x2 = rectpuls(t,20e-3);
subplot(211),plot(t,x1), axis([-0.1 0.1 -0.2 1.2])
xlabel('Time (sec)');ylabel('Amplitude'); title('Triangular Aperiodic Pulse')
subplot(212),plot(t,x2), axis([-0.1 0.1 -0.2 1.2])
xlabel('Time (sec)');ylabel('Amplitude'); title('Rectangular Aperiodic Pulse')
set(gcf,'Color',[1 1 1]),



The gauspuls function generates a Gaussian-modulated sinusoidal pulse with a specified time, center frequency, and fractional bandwidth.
          gauspuls('cutoff',f,bw,[],att)
                    f- cutoff freq
                    bw- bandwith (0 to 1)
                    att- attenuation value (in db)

The sinc function computes the mathematical sinc function for an input vector or matrix. The sinc function is the continuous inverse Fourier transform of the rectangular pulse of width 2*pi and height 1.


%GUASSIAN PULSE
tc = gauspuls('cutoff',50e3,0.6,[],-40);
t1 = -tc : 1e-6 : tc;
y1 = gauspuls(t1,50e3,0.6);

% SINC PULSE
t2 = linspace(-5,5); % linearly spaced vector (LSV)
y2 = sinc(t2); % sinc for LSV
subplot(211),plot(t1*1e3,y1);
xlabel('Time (ms)');ylabel('Amplitude'); title('Gaussian Pulse')
subplot(212),plot(t2,y2);
xlabel('Time (sec)');ylabel('Amplitude'); title('Sinc Function')
set(gcf,'Color',[1 1 1]),



Pulse Trains:
          The pulse trains can be generated using the pulstran function. Below examples shows how to use this function to generate Rectangular & Gaussian pulse train.
%RECTANGULAR PULSE TRAIN
fs = 100E9;                % sample freq 100GHz
D = [2.5 10 17.5]' * 1e-9; % pulse delay times
t = 0 : 1/fs : 25e-9;      % time 0-25ns
w = 1e-9;                  % width of each pulse
yp = pulstran(t,D,@rectpuls,w);

%GUASSIAN PULSE TRAIN
T = 0 : 1/50E3 : 10E-3; % 0-10ms @ 50KHz sample freq
D = [0 : 1/1E3 : 10E-3 ; 0.8.^(0:10)]'; % pulse delay times, repeat every 1ms, optional attenuation factor 0.8 from 0-10ms
Y = pulstran(T,D,@gauspuls,10E3,.5); %10KHz, 50% bandwidth

subplot(211),plot(t*1e9,yp);axis([0 25 -0.2 1.2])
xlabel('Time (ns)'); ylabel('Amplitude'); title('Rectangular Train')
subplot(212),plot(T*1e3,Y)
xlabel('Time (ms)'); ylabel('Amplitude'); title('Gaussian Pulse Train')
set(gcf,'Color',[1 1 1]),





If you enjoyed this post plz let us know your views via comments.
This helps us to do much more better.
Thankyou.


Search Here...