Some AVR microcontrollers have Timer2 which can operate in. None of those programmers used the RTC clock that is described in this. The AVR ATMega168 microcontroller is used as the I2C’s master whiles the DS1307 RTC is used as the I2C slave that provide accurate date and time function. The TIMER0 peripheral inside ATMega168 microcontroller is used to read the DS1307 RTC register every 1 second and display the value to the 2×15 LCD.
Ds1307 Bascom Programming Of Micro Average ratng: 3,5/5 2068votesThe DS1307 Serial Real Time Clock, which incorporates a 2-wire serial interface, can be controlled using an 8051-compatible microcontroller. The DS1307 in this example is connected directly to two of the I/O ports on a DS5000 microcontroller and the 2-wire handshaking is handled by low-level drivers, which are discussed in this application note. Blog Entry Using Maxim DS1307 Real Time Clock with Atmel AVR Microcontroller May 11, 2009 by rwb, under Microcontroller.
Become a subscriber (Free)Join 29,000 other subscribers to receive subscriber sale discounts andother free resources.Name:E-Mail:Don't worry - youre-mail address is totallysecure. I promise to use it only to send youMicroZine.A Real Time Clock IC (DS1307) project using the PIC micro.Making A Real Time Clock (RTC) is simple if youuse a helper chip such as a DS1307 because you do not need to keep track of thelength of each month or account for leap years. It is all done for you, plusyou get the benefit of a battery back up system that means it won't lose thedata or time when you turn off main power.This PIC project uses an I2C (or IIC) Real Time Clock IC (DS1307) and a fourdigit seven segment display to create a standard desk clock.Note: If you typed DS1703 Real Time Clockto find this page you probably mis-spelled the chip type.Anyway you can find a DS1307 (RTC) Real Time Clock IC project and information onthis page.Note: This RTC project has been updatedwith easier to use software i.e. The software loaded into the PIC (Note thecompiler is free for. Note: Address 3f is used in this project as a check to seeif the clock needs initialising and to store the upper year digit (for easiercoding).The last address 0x08 is the CONTROL address and it determineswhat is generated at the SQW/OUT pin. You can control the level directly viaI2C or set it to 1Hz, 4096Hz, 8192Hz, or 32768kHz.
In this software it is setto 1Hz and used to drive an LED that can be used as a back light for the4x7-segment module (if you shine a light through the module you'll see the twocentral holes (like a colon character) that are between the left and right setsof two 7-segments. This is usually used to flash seconds so placing the LEDbehind this will achieve that operation.In the same way as the I2C pins you need to add a pull-up toV+ at the SQW/OUT pin to see any output signal as it is an open drain output!or as in this circuit, an LED and 470R resistor are connected in series and tothe +5V power.
The other end goes to the SWQ/OUT pin of the DS1307. DS1307 Specification AccuracyWatchcrystal spec typically 20ppmCompilerMikroelectronika MikroC Compiler Free!Target16F88(re-targettable to other PICs that have Analogue input AN0).Software levelMedium.Software notesSwitchingbetween i/p & o/p to read analogue/drive display.
Using I2Croutines.Hardware levelEasy.Hardware notesSpecialcare must be taken in placing the DS1307 and the crystal.Project version1.02Project filesEnteryour details to get the Download Linkand get the microcontroller newsletter. (Note: Your email is safe it will neverbe sold or rented).You willget All the C source code and hex file.Note: Check your email for the project code downloadlink.DS1307 Control BitsThere are two specific 'gotcha' type controls embedded in theaddresses which make using the chip slightly more complicated. DS1307 Registers Clock halt (CH)The most important is the Clock Halt Bit (CH) which is bit 7 ofaddress 0.
This is the register that controls 'seconds' and the CH bit has tobe preserved otherwise the chip stops the clock. Writing zero to this bitresets the CH bit so that the clock runs.Note: You have to reset the CH bit to zero to let the chipoperate!Warning: The default state of theDS1307 is undefinedso you must clear the CH bit to start the oscillator.In general you should leave this bit at zero and only set it ifyou have to. This bit is contained within register zero which is also the'minutes' and 'seconds' register.
In general keep this bit at zero unless youare updating the seconds part of the register (you don't want the secondschanging while you are editing them). DS1307 24/12 Hour controlThe second is the 24/12 hour control which is bit 6 of address2. It is set high for 12 hour mode and low for 24 hour mode.
In this project itis set low for 24 hour mode.The problem with these two bits is that you have to preservethem when accessing the registers to write data and ignore them when readingout values for display. Its not a big problem and you can see how it's donewhen you look at the code (see function editDS1307 and the 1st 2 casestatements for address 0 (CH) and 2 (12H/24H) ). DS1307 32kHz oscillatorSurprisingly making an accurate 32kHz oscillator is a difficulttask (much more than a high speed oscillator e.g. A MHz crystal oscillator).This is because low speed oscillator drivers are designed for low poweroperation. That means high impedance and therefore low current which makes thedriver extremely sensitive to noise (or any nearby signals which cancapacitively couple to the crystal wire).Using the DS1307 lets you put the crystal in the least noisypart of the board.
In addition it sets the crystal load capacitance which iscritical in making the crystal oscillate at exactly 32kHz - controlling itsinitial error i.e. For the specified ppm error value the load capacitance mustbe exact. Note: A common way of calibrating a crystal (not in thisproject) is crystal pulling or changing the capacitance at one crystal pinrelative to the other - so load capacitance is crucial.The DS1307 loads the crystal with 12.7pF so you need to buy acrystal that is defined to use this load capacitance. Circuit layout alsoaffects the capacitance at the crystal pins so you must keep the crystal asclose as possible to the chip and the tracks from crystal to chip must beshort.To ensure the crystal oscillates correctly you must ensure that:. Crystal uses 12.7pf load capacitance (correct crystal type). The crystal is close to the IC.
The tracks are short. The chip supply has lots of decoupling (capacitors from +5V to GND).
E.g.A 100n and a 10n. There are no signal tracks near to the crystal. For a pcb: It has a guard ring and a ground plane and away from digitalsignals.If you are doing a board layout there is good advice in the PIC16F88 datasheet (Timer 1 section) on crystal pcb guard rings. Dallas recommendsApplication note 58 which I have not read yet.
DS1307 Power failure.The DS1307 detects a power failure if its input voltage (Vcc)falls below (VBat) and automatically switches to the Vbat supply input (youshould use a lithium 3V battery here as the backup battery). It also inhibitsI2C control signals until Vcc is 1.25 x Vbat so you won't be able to put baddata into the chip as the power is failing! Real Time Clock Design Input keysTo save microcontroller pins there are four input keys whichare all connected to a single analogue input pin. This pin also drives one ofthe seven segment display LEDs so it has to be switched between input (to readthe analogue voltage) and output (to drive the led).Note: This works because the analogue input is switched toreceive analogue for only (150us approx) there is a 100us delay to let theinputs settle (just a guess and could be made lower - but it is not critical inthis application).
Attention, Internet Explorer UserAnnouncement: VMware Communities has discontinued support for Internet Explorer 7 and below.In order to provide the best platform for continued innovation, VMware Communities no longer supports Internet Explorer 7.VMware Communities will not function with this version of Internet Explorer. Opengl support for vmware esxi 6 download.
Then the input signal is read. Because of persistence ofvision (on which the entire display methodology depends) your eye can not seethis missing light pulse so it looks like the display is completely steady!Each key pulls the analogue input to a different voltage levelwhich you can easily read using the ADC (RA0). Note: Readings are approx since resistor tolerance will be 10% for standard resistors.
7 Segment DisplayThe display is made up of four 7 segments built into aconvenient block where all 8 led drive lines are connected together. Youcould wire up individual 7-segments to achieve the same result but doing it ona soldered breadboard is a pain. The block just saves you effort (and errors inwiring). So this results in 8 data lines and 4 digit select lines.Initially I used RA0 to RA7 as the data line drivers andRB2,5,6,7.
Then I realised that RA5 is only allowed to be an input because itis also multiplexed with the reset pin MCLR. Since it had been wired up thisway the simplest solution was to eliminate RA5 but how do you do that withoutchanging all the drive data definitions?When eliminating RA5 I moved RA6 and RA7 down to bits b5 and b6so this leaves the LED drive for the decimal point unconnected but that is OKsince we are not using that part of the 7-segment display.So the solution is to use a helper function that maps the bits6,7 to bits 5,6 just before outputting the data to the 7-segment LED bus andthe function has an obvious name:moveb6b7tob5b6(Byte num). TIP: The MikroC IDE has a usefultool for generating the hex codes for segment drives inMenu-Tools-Seven Segment Editor. Digit Select linesThe digit select lines are each driven by a transistor switchthat allows more current if needed ( note I have not measured the exactcurrent drawn as it depends on the refresh rate of the display).
Display Refresh and current limit resistorsYes there are none! Between the RA bus and the LED drivesthere are no limit resistors.Why?In all other circuits you can see them. I chose not to use themsince the display is only ever driven in refresh mode. If it were drivendirectly then the LEDs would blow up.
A commercial use of this technique is the.If you are uncomfortable with this then add 8 off of 330R or470R resistors to limit the maximum current to each LED (e.g. If the are drivenpermanently during testing) from each drive RA bus to the 4x7-segmentdisplay.The reason that it works is to do with heat generated - as thecurrent flows in the LED the junction heats up and if you drive too muchcurrent then it melts the internal wires - which is where the max. Currentlimit comes from.When driving the display in refresh mode the display is held onfor a very short time compared to the time it is held off and this defines anaverage current that is within the current limit of each LED.Hey. Don't knock it.
It works fine.promise. Note: The idea comes from chipdesign where the current drawn by the device depends on the switching speed ofthe system since for FETs maximum current is drawn when both upper and lowerFETs in a switch are on i.e. During the transition from current level to nexti.e. When switching. DS1307 Project OperationWhen the system powers up the ram location 0x3f is checked for value 0x20.If this exists then it means that the backup battery has saved contents of theRAM and all the registers have therefore been initialised. So the softwareskips the initialisation sequence. Note: I am assuming you are going tobe sensible and set the year high digits to 20 as V1.02 allows you to edit thisvalue - just make sure it is 20 if you power down and up otherwise it will setup default values i.e.
It will reset the other registers to specificinitialisation values.If 0x20 is not found then the Real Time Clock IC is initialisedto the following values:AddressInitialisation value0 Seconds0x59 (bit 7 cleared).1 Minutes0x592 Hours0x24 (bit 6 cleared).3 Day0x074 Date0x315 Month0x126 Year0x99 (low digits)3f Year0x20 ( highdigits)These are all Binary Coded Decimal numbers which the Real TimeClock IC works with. Note that the initialisation values have been chosen soyou can easily understand what the display is showing but from V1.02 this isnot as important as you can hit key 3 to get on what isdisplayed.
Pseudo TextDisplayHowever when re-visiting the project it turns out that it is adifficult task (figuring out exactly what is on the display especially if it is8.20pm in 2014 i.e. All the numbers are identical) which is why pressing key 3(when not editing a value) flashes the display at a flicker (slow) rate andindicates what you are looking at with the following 7-segment outputs. Mode7-segment codeMeaningMODEHRSMINSHrnnHours and minutesMODEMINSSECSnnSeMinutes and secondsMODEDAYMONdAnnDay and MonthMODEYEARyEArYearMODEINITInItInitialisationMode buttonPressing mode button cycles the display showing different dataafter each button press. The following display sequence is followed:. Hours, Minutes. Minutes, Secs.
Day, Month. Year.Edit, Up and Down buttonsTo change a value the Edit button must be pressed (Key2).
Whenit is, the left hand two digits are flashed on and off. Now the Up button (key3) andDown button (Key4) let you edit the value.Hitting Edit again flashes thetwo right hand digits and you can change the value as before. Hitting the Editbutton or the Mode button again then exits the edit mode.The clock is only stopped when editing the Minutes/Secondsdisplay and restarted at the end of the edit sequence or when the Mode buttonis hit (the routine checkstartds1307 will not change the state or write tothe oscillator register if the clock is already running i.e. The clockoscillator is only started if it was previously stopped). This lets you set theseconds accurately but does not disturb the clock in other modes. Setting the Clock AccuratelyNote I am not sure why but it may be how the DS1307 works youhave to set the time 1 second in advance of the desired transition time.say the clock currently read 1328 13 minutes and 28 seconds toset the time fairly well edit the time to 13 45 then hit the edit key when yourclock you are trying to synchronize to is at 1344. This seems to get theseconds changing at the same time as the source clock. This is probably due tothe double register set within the DS1307 updating only at a specific time.
Real Time Clock IC hardware Real Time Clock IC projectClick digital clock schematic to open a pdf document. Note: While programming the PGD andPCK lines are toggled and these connect to the Display so you will see someLEDs light up during the programming sequence - Don't worry aboutit!
DS1307 Project Block DiagramThere is nothing really difficult about the project except for placing theDS1307 away from noise sources and decoupling it as mentioned earlier. Real Time Clock IC project Software Project filesCompiler project filesThere are a lot more for 6.4.0 (see the download file).C Source files.16F88RTCDS1307.cI2C.cHeader files.bit.h - bit manipulation macrosI2C.h - definitions for I2C operation.Output files16F88RTCDS1307.hexDS1307 Code Description16F88RTCDS1307.cThis contains the main routine and support functions forcontrolling the DS1307.I2C.cThis contains the software implementation of I2C (clock stretching has not beentested).
To change the PORTs/pins alter the #define statements at the start ofI2C.c Functions. init. initports. initds1307. readds1307.
writeds1307. stopds1307. startds1307The above functions are all self explanatory. Those below need a bit of explanation.Function int2segConverts a number into the required output value for PORTA to drive theseven segment display. The internal array ret holds the 7-segment values -these are pure 8 bit values as if all data lines to the 7-segments areconnected. Moves bits around in a byte to account for the fact that RA5 is not used.Function ReadANAkeysThis routine decodes the analogue levels into a specific keypress. It returns a value from 1-4 representing keys 1-4.
On the schematic key1is pb1 and should be located on a board at the top.This calls decodeANAkeys to determine the key pressed.In this routine the analogue input is turned on, a delay of100us is used, then the key decoded, then the analogue input returned to adigital output.Note how this is using the RA0 pin as both an analogue inputpin and as a digital output pin.This works for two reasons:. The system is not interrupt driven. The time to read an analogue port is small compared to doing everythingelse. Note: If this was interrupt driven code the portA (LED drives)writing interrupt would be required to read the analogue port so that the pindirection was not changed during a read i.e.
You would use that interruptroutine since it would know when it is safe to read the analogue value.Because it is not interrupt driven the code is always followinga set order of operation therefore it can never turn the port back to an outputwhile the analogue pin is being read.Your eye can not see the difference in 100us when the port isread - it really just extends the led off period by 100us. Function decodeANAkeysThis is a simple range detect that returns the key pressed ifthe analogue value falls within a specific range. Function editds1307This is used in the 'main' routine to allow up/down edit of the currentDS1307 register values. It takes as input the DS1307 address and directiondesired and increments or decrements the register value depending on dir andalso limits the value that is updated to keep it in a valid range.Note how it manages the 'problem' addresses that contain CH and12/24 Hour bits as well as the desired value.Also note how the 'one' routine uses different upper limit andlower limit controls to control operation for individual registers i.e.depending on register use the values are constrained to specific limits. Function clockdisplayThis function provides the main display ability ofthe system and it works slightly differently to traditional code.
This code isdesigned to be re-entrant and to do a different job every time it is called itis effectively a state machine with the state stored by the static variable'digit'.Each time it is called digit is incremented andthis chooses the next segment driver pin on PortB.Since the function also takes two binary codedvalues as arguments (one for the left two 7-segment digits and one for theright two 7-segment digits). It can display a different digit every time thefunction is called. So by calling the function fast enough the 4x7-segmentdisplay appears to be constantly on due to persistence of vision.The complexity in this routine is for selectively blanking leftor right pairs of digits so that they can be flashed on and off. Othercomplexity is preserving the control bits at addresses 0x00 and 0x02. Note: Observe the coding of the column pins on PortB since they are notorganized linearly.Function mainThe array idx holds two values that are the addresses into the DS1307clock address space. Idx0 holds an address that allows display on the lefttwo 7-segments while idx1 holds an address that is used to display data onthe right two 7-segments.By changing the idx values, specific register values in the DS1307 can bedisplayed.
For instance the code for selecting hours and minutes to bedisplayed is. Clockdisplay(addr1, addr2, blank).is used to update the display using this information.The variable 'edit' is used both as a flag to indicate that editing is inprogress and as an index into the idx array to specify which or the two arrayvalues is being incremented or decremented. If 'edit' has the valueFINISHEDEDIT (=-1) then editing is not taking place or it has just finished(by the user pressing key two after the right hand digit set has beenedited.You can see how this works in the two case statements case 3: and case: 4 forup and down editing of a value respectively.
If not editing then the testfunction or displaymode function is called instead.Flashing a digit set is performed by controlling the blankIdx value at the endof the main function. If it is -1 then no value is displayed using thefunction clockdisplay. The actual timing is controlled by the variable'flash' that is incremented every pass round the while loop. 'flash' is kept tosimple values of 60 and 30 and half the time (up to 30 the digit is on while itis off for the other half). Note: If you change the update rate of the routines you need to manually adjustthis flash rate as it is not interrupt driven and will therefore change.Key OperationIn main keys are detected and avalue returned in the range 1-4Key actions:KeyKey functionkey action1ChangemodeSelects the displayed data e.g. Hours minutes,year etc.2Enter editmodeEnter edit mode for the current data displayand edit left.2If in edit modemove to next digit or exit mode.3If in edit modeIncrease the selected digits value.3Not in edit modeDisplay Pseudo-text indicating what is on the display.4If in edit modeDecrease the selected digits value.4Not in edit modeEnter test mode (each press moves to display diff. Led)Note 'Not in edit mode' are extra features.TEST and supplementary operations for the Real Time Clock Function test - Test 7-segment connections.You can use this to check your 7 segment displays to see if they are connected correctly.This routine is executed when not in edit mode and key 4 is pressed.At each press of key4 a different led is lit (the same one in eachindividual 7-segment).
Note: See the schematic for led names on each 7-segment. Function displaymodeThis routine is similar to test except that it takes in a mode value that isthe one being used in the main routine.
Note: The interesting way of using the RA0 pin as both adigital output and as an analogue input. See onthis.And that's it - enjoy. An Exercise For YouA simple exercise that you might want to do is to add an alarmfunction - at the moment 1552 bytes of flash are used up leaving room for quitea lot of additional code 2k -1552 = space left. Adding an alarm function wouldsimply be a matter of adding an additional definition:e.g. And using some of the DS1307 RAM to store the alarm setting(since it is preserved by the battery backup when the power fails).You would need to change the code where the mode setting isupdated and the pseudo text code as well.
In the main loop you would read thecurrent Hour,Minute setting until it matched the stored value and then generatean alarm.For output there is a spare pin RB3 - there is a 10k pull-downbut this is not useful if the part has been taken out of LVP mode byprogramming it using the ICSP programmer - so it is free for you to attach apiezo disc (remove the resistor - prob. Was not really needed anyway!).Show Index.