================================================================================================================================================

Saturday, June 23, 2018

Relay-Timer Circuit with RTC (for auto-operating appliances) using AtmelStudio or Arduino




Hi friends,
     it's been years since I put up a new post here. So, starting again with a simple circuit, based on ATmega8, might be useful for newbies in AVR, RTC, Relay, etc.This is RTC based relay operating circuit to automatically power ON/OFF any electrical device/appliance at a preset time. 
    The necessity behind it was this: I had started taking a 230V AC electrical Tiffin (lunch) box to office a few months back, which takes minimum 30 minutes to very slowly heat up the food (it's kept slow heating as the idea is to just heat the food without re-cooking it). That means it's necessary to turn the box ON 30 minutes before lunch-time. And it happened quite a lot of time that I simply forgot or could not power on due to a meeting in another building. So, one day I quickly cooked up this circuit as I was already having all the required components (including an ATmega8 development board and a relay module, to minimize the soldering job).
    Before anything further, if you try to make this circuit, WARNING!! High Voltages are involved here, extreme care is necessary while testing/operation. Ensure proper insulation for the high-voltage lines.
    This circuit can be used for powering any electrical device by setting start and stop time, which is stored in EEPROM of ATmega8, so no need to set again upon power off. RTC (based on DS1307) is used for similar reasons, no need to keep the circuit ON when not necessary, or during power off, it will maintain the date/time running (with the help of the common 3v Li button-cell). RTC setting or start/stop time setting can be changed anytime using three push-buttons provided onboard.
    Now, the main components: The microcontroller is AVR ATmega8, small enough and with sufficient flash for the code required here. Initially (before making the custom-made PCB shown in the above pics), I used a off-the-shelf available 28-pin AVR Development board from Extreme Electronics. The board is shown here:

    Using such a board avoids soldering the IC base, power supply components, ISP connector, etc. And it's having some user area for soldering, which was sufficient for this project.
    The Dual-channel Relay board used initially is from EmbeddedMarket.com:


    This module is having two independent relays with transistor circuits for activation. The VCC supply line of the coils here are connected with 9V or 12 V DC (as per the DC adapter used to power the development board) and the AVR port lines are connected to RL1 and RL2 terminals. Two devices can be independently operated with this module by connecting the AC live input to the NO (Normally Open) terminal of the Relay and taking the output from C (common) terminal to the electrical device live input. The return line of the electrical device can directly go from device to the mains, without connecting to this unit. (Note: As I was having only one device to control, I passed the Phase (Live) through one relay and Neutral through the another relay. The program operates both the relays simultaneously to power the electrical device, i.e.Tiffin-box in this case).
    Here is the Proteus simulation screen-shot (during simulation, LEDs are used in place of the relays to check the functionality and the serial terminal is unused):


 
  Following is the simulation using ATmega328 (Arduino):


 (The Proteus simulation files are included in the source code download at the end of the post).

    As shown, upon powering on, after displaying a welcome message, the LCD displays current date and time, and the output status (via two relays). The output ON is also indicated using a Red LED on the circuit. The terminal (UART) in the circuit is kept extra, in case someone wants to use terminal instead of LCD and push-buttons to display/set timings (This further reduces the hardware onboard, it will add only a UART-USB converter module for PC/laptop connection, which are quite commonly available).
    The program reads the set-time in EEPROM by checking for a valid EEPROM signature. If time is not set, it sets default time of 1230 HRS for start time and 1300 HRS for stop time. Whenever a new time is set, it's stored in the EEPROM and used during operation thereafter.
    The quickly made proto of the circuit with whatever came handy is shown here (underneath the LCD are the AVR and relay boards with the rest of the circuitry):



       The 230V lines are properly screwed and totally insulated using glue-gun inside the box, including the relay terminals, so that not even a single strand of the wire comes out of the insulation.
     Of course, the circuit can be totally tested (or time can be set/ changed) without connecting the 230V lines, as we can confirm the continuity of the relay line by checking with multimeter. The high voltage line is necessary only during the actual operation.
    Later on, the schematic and layout of the PCB were designed using KiCad (latest version 5.0), as KiCad has recently become a really great tool (and free, too!), as compared to my quite earlier experience with it. I instantly liked it even better then the EAGLE lite, which I had been using so far.
The schematic is given here (when using Arduino, replace ATmega8 with ATmega328 in the circuit, in the same PCB):


       The PDF schematic can be downloaded from here.

The operation of the circuit is described here:

Circuit Operation:
--------------------------------------------
For setting RTC Date/Time:
  1. Press 'SET' button and Power ON the circuit, keeping the button pressed while the circuit is starting.
  2. "RTC Setting.." message will be displayed on the first row of the LCD.
  3.  Release the 'SET' button "Date: XX" will be displayed on the second row of the LCD, where XX is the existing current date as per the RTC.
  4.  Press 'UP' or 'DOWN' button to increase or decrease the Date. When desired date is displayed, press 'SET' button to store it
  5. "Month: XX" message will be displayed, where XX is the current month as per the RTC
  6. Press 'UP' or 'DOWN' button to increase or decrease the Month. When desired month is displayed, press 'SET' button to store it
  7. "Year: XXXX" will be displayed, use 'UP'/ 'DOWN' buttons to change the year and then press 'SET' button to store the year value
  8. Then "Hour: XX" will be displayed, set it as per the previous steps and also set next "Minutes: XX" similarly, and store using 'SET' button.
  9. When the Minutes is set, "RTC Setting" mode is over and normal operation resumes, where the LCD will display Date and time in the first row and O/P: ON/OFF status in the second row.
 Normal Operation:
  1.  When the circuit is powered ON without pressing the 'SET' button, it displays "Welcome, -Relay timer-" message for two seconds and then directly enters into the normal mode
  2. During the normal operation, the LCD display will be as per the above step 9. The Date and time are continuously updated on the display every second
  3. In the normal operation, whenever the RTC time matches with the Start Time, the Relays are energized, connecting the output lines with the respective input lines. 
  4. When the output is ON, as soon as the RTC time matches with the Stop time, the relays are turned OFF, cutting off the output
  5. The output ON and OFF are displayed on the LCD as well as indicated by Red LED ON and OFF, respectively
Setting Start/ Stop time:
  1.  Start and Stop time can be changed anytime  during the normal operation
  2.  Pressing the 'SET' button during normal operation displays currently set values of Start and Stop (End) times in "S:HH:MM E:HH:MM" format in the second row, where 'S' indicates Start time and 'E' indicates End (Stop) time. 'HH' and 'MM' are hours and minutes, respectively. The first row continues to display current date and time.
  3. During step 2, if 'SET' button is pressed again, display goes back to normal operation. But if 'UP' or 'DOWN' button is pressed instead, the program enters into the Start/Stop time setting mode, where "Start Hour: XX" is displayed in the second row.
  4. Use the 'UP'/'DOWN' and 'SET' keys to adjust Start Hour, followed by Start Min (Minutes), then Stop Hour and Stop Min. Each value is stored by pressing the 'SET' button.
  5. After the Step 4, the new values are stored in EEPROM and normal operation resumes.
       Here are two more views of the operational unit:
     


 Notes:
  • After RTC and Start/stop times are set, no intervention is required for circuit operation
  • Whenever necessary, the circuit can be switched off, the date/time settings will be maintained
  • If the circuit power is OFF and the start time is missed before the power is ON, the circuit will not set the o/p even if the Stop time is still quite away. It will set the o/p only when the next start time match with RTC. (This can be changed by minor modification in the code, if necessary).
  • Warning again, proper insulation and extreme care from high voltage line is must!! Never keep you high voltage outlet pins 'Male' type, always use socket type. Use 'male' types only for the high voltage 'inlet' pins.
    So, for last couple of months, I connect the Tiffin with the circuit (first thing after reaching office), using standard 230V AC plug, and power ON the circuit, check the display for normal operation and then continue with my work. The Tiffin gets ON and OFF as per the set time before lunch. At lunch time, I turn off the power (coz it's not necessary till next morning) and enjoy the hot meal!! The power can be kept ON also, if desired. For example, in case if you want to water your plants periodically by turning on the electrical motor, whether you are available nearby or not.

Here is the complete source code in AtmelStudio7 and Arduino project files along with the Proteus simulation files (please ensure programming the fuse bites for proper clock frequency values). When using Arduino, ATmega8 needs to be replaced with ATmega328:

Downloads

Source Code (AtmelStudio) and Simulation Download (ATmega8, @8 MHz internal clock)

Source Code (Arduino) and Simulation Download (ATmega328, @16 MHz External clock)

KiCad Project Schematic, PCB and Gerber files


Datasheets/ Links:   ATmega8,   ATmega328,   DS1307,   Arduino Website


Enjoy!!

Thanks & Regards,
CC Dharmani 
--------------------------------

Tuesday, May 10, 2011

microSD ATmega32 Data-Logger



Hi friends,

aim of this project is to present a way to store a large quantity of data into microSD card in files with FAT32 format. Here, ATmega32 is used for data collection and microSD interface. The data is received from in-build 8-channel ADC of ATmega32. One channel is used for reading temperature from LM35 sensor and remaining channels are used for simply reading voltages and storing them.

This project can be used to interface 8 different sensors with ADC of ATmega32, similar to the LM35 used here. The data is stored in CSV (comma separated values) format, which can be read using a PC/Laptop with Microsoft Excel or other compatible software. A snapshot of the excel file is given later in this post.

This project is an example of how to use the microSD FAT32 library presented in my earlier post. In that post, the files were created using hyper-terminal and entering data with the PC keyboard, since that demonstrates the file creation and it's easy to debug. But many users have requested to make the file creation independent of the terminal, done inside the microcontroller, so I'm showing here how to use those functions independent of terminal. If you have directly landed on this page, it would be more helpful if you visit the original post first as it would be a better starting place for learning SD or FAT32 functions (also Check out my this post for updated version of this project with 16x2 LCD and DS1621 temperature sensor

Here is the schematic (click on the images for larger view or download PDF):

The project contains RTC interface (for date and time storage), RS232 (for connection with PC) and a microSD module. Here, the hyper-terminal connection is required only for setting RTC date and time. Once the date/time are set, the RS232 connection is not required anymore for normal data-logging operation (It can be used for debugging purpose if there is a problem).

The microSD module used here is from eXtreme Electronics.
The module is shown in the figure here. Other than the microSD socket, this low-cost module also contains on-board 3.3v regulator for the microSD card, a 5v-3.3v level converter and other safety features required for the card. This module is used here as it provides a stable interface and makes the the card compatible with 5v supply and 5v signals of microcontroller.

The module is available at: http://store.extremeelectronics.co.in/MicroSD-TF-Module.html

The schematic also shows two LEDs and a push-button. The LEDs are used for indications of power and recording and the push-button is used to start-stop recording.

Operation of the circuit:
-----------------------------------------------
For setting RTC date/time (or for debugging mode):
  • Connect the microSD module, insert the microSD card
  • Connect the RS232 cable with the circuit. Set-up hyper terminal with 19200 baud, no parity, 8-bit data, 1 stop-bit and flow-control as 'None'
  • Connect the power cable and power on the circuit while keeping the push-button pressed
  • Green LED will glow in the circuit board
  • A menu will be displayed on the Hyper terminal as shown in the figure below. Select desired option and follow the displayed instructions
  • When date/time is set or debugging done, select option '0' to come out of the menu and start functioning a s data-logger
  • At this point, the RS232 cable can be removed


Operation as Data-Logger:
  • Connect the power cable and power on the circuit
  • Green LED will glow
  • Whenever the data-logging is required, press the push-button
  • Red LED will glow, indicating that the recording has started
  • To stop recording, press the push-button again, recording will stop and red LED will turn off
  • Files stored in the card can be read using a PC card-reader or using hyper-terminal with the circuit started in debugging mode


The operation is very simple as it uses just one push-button and an LED indication. In case of any error in accessing the card, red LED will blink continuously. In such a case, you can start circuit in debug mode (with terminal) and see the error messages.

Files are stored with the date as a name and .CSV extension. For example, data-logging done on 10 May 2011 would be stored in "10052011.CSV" file. Since the date is the name of file, everyday a single file is created and all the data recording done in a day goes into single file, no matter how many times the recording is stopped/started. First column of the file shows date, second shows time and next 8 columns show data from the 8 channels.

A file created during testing is shown in the figure below, where 5 sec interval was set for measurements (click on the image to enlarge it). Here channel-0 was used for LM35 temperature sensor, and remaining channels measure voltage. 5v was connected to channel-1 and 3v Li cell was connected to channel-3 (Channel 2 & 4 show some small voltages due to noise from voltages connected to nearby channels, which can be corrected by using bypass caps).


The interval between two measurement cycles is defined in main.c file, which can be set as per the user requirement. Basically, the program forms a dataString in every measurement cycle and appends this string to the file, if the file already exists or it creates a new file (for example, during the first recording in a day). You may go through the comments in the source code file for more info.

Note: Make sure that RTC circuit is properly connected, otherwise the code will simply hang waiting for receiving date & time from RTC

New Version: Check out my this post for updated version of this project with 16x2 LCD and DS1621 temperature sensor. Project Code with FatFs library is also shared there.

Download project files
--------------------------------------
The source code is written in AVR-GCC format using winAVR with AVRStudio-4, complete AVRStudio project folder can be downloaded from here:

- Download Source Code

Download schematic:
- Schematic (PDF)
- Schematic (EAGLE)

References:
--------------
Visit my earlier post for the references on SD card & FAT32 which are given at the end of the post

Wednesday, December 8, 2010

microSD FAT32 testing using Visual C++


Hi friends,

this post presents a way for testing and learning the FAT32 system on microSD/ SDHC cards without building the hardware with microcontroller, thanks to Henry Yiu.

This project uses the FAT32 library available in my previous post, but does away with the microcontroller part. So, you can use this code with a PC and USB card reader and get insight of the FAT32 data structure by accessing data from the card in raw as well as in FAT format.

This code can be used as a confidence building step for those who are not comfortable with directly building the hardware part. Once the FAT is understood, one can go ahead with development of hardware and customization of the software.

This may look like hardcore software thing, but it's not so. It can be tested by anybody with little knowledge of programming and determination to understand the FAT / sd card formats.

Step by step procedure for testing of the code is explained later.

Here are the Henry's words for the project:
-----------------------------------------------------------------------
When trying to build a microcontroller to access an SD card, I came across this web site which details the hardware and software of how to use an Atmel AVR microcontroller to access an SD card. But I wanted to test out the FAT32 file system code before actually building the hardware. Therefore, I wrote this code to run on Visual C++ to enable me to test the FAT32 code without actually building the hardware.

Tracing the code can reveal many compatibility problems between how the official FAT32 documentation and how Microsoft Windows actually implement the FAT32 system. There are a few interesting things I found for Windows XP. Maybe you can find more using various trace methods and many different brands of SD cards.

The things I found are, for example:

1. After adding or deleting files in Windows XP, the FSinfo next free cluster upper 16-bit is always zero.
2. Adding new files in Windows XP updates the directory structure, but does not set the next entry to empty.
3. Deleting files in Windows XP does not set the FSinfo structure next free cluster to a lower numbered cluster of the deleted file.

Recommended software:
---------------------------------------------------------------------------------
Microsoft Visual C++ Express: Not available anymore, but it has been replaced with Visual Studio Community Edition. (For comparison details with Visual Studio Express,please visit this spreadsheet).

HxD Hex Editor and Disk Editor
The DevCon command-line utility functions

How to use: Only five files:
MAIN.CC, SDCARD.CC, FAT32.CC, FAT32.H, GLOBAL.H.

Use Microsoft Visual C++ Express to build these files with the default built option. Then you can step through the program to learn the boot record structure, the FAT table, and how clusters are linked together. You can also use HxD Hex Editor (Extras -> Open Physical Disk) to study the SD card content. Since data is cached in Windows, you need to unplug and plug the USB card reader for write or delete command to be visible in Windows. The DevCon utility allows you to do so without the need to actually do a hardware plug and unplug. Then you can test the FAT32 system using a batch file.

Enjoy
BR - Henry Yiu

You can download the complete project folder from here:
microSD-FAT32 with Visual C++

Many thanks to Henry for allowing to share his work

Here is the step-by-step procedure of how to use the code:
----------------------------------------------------------------------------------------
(well, this assumes that you have already done some basic background study on FAT32 and microSD cards, may be by reading a few articles on them, since some theoretical knowledge would really help in making sense of the results you get)

(the folder which you download already contains the .exe file, but we'll assume that it is not there, to make the procedure complete)

1. Install and open VC++ express

2. Create a new project (select 'empty project' when asked). Enter the location and project-name. Here we'll select project-name as 'sdcard', and location as desktop

3. Project window will open. Now, go back to desktop and copy the 5 files (MAIN.CC, SDCARD.CC, FAT32.CC, FAT32.H, GLOBAL.H) from the downloaded folder, into the folder created by the VC++

4. Go back to VC++ window and add the header files and source files into respective categories displayed at left side window panel. The panel will now look like this (here main file is open):


5. Now, from the top menu-line, under 'debug', select 'build solution'. This will build the project files. The build window at the bottom of the page is shown in this figure:


6. Now, select 'start debugging' under the same 'debug' menu. This is to make sure that the .exe file is generated. Okay, now you are ready with the .exe file. It will be stored in the 'debug' folder inside the project directory. In our case directory is 'sdcard' on the desktop.

7. It's time to test the .exe file. So, connect the USB card reader, insert a microSD card (make sure the card is already formatted with FAT32, you can also store some files for checking the read feature of the code)

8. Open windows command prompt. In the command prompt, go to the project directory, 'debug' folder. Now, type 'sdcard' or 'sdcard.exe'. This will display the available options. This is described in this figure:

9. Using the command shown in the above figure, you can select 'read', 'write', 'delete' etc. options, as per the command format. After every command executed, it would display 'success!'. If any error, it would display an error message. Some of the file operations are shown here:


10. Once you have performed some operations in last step by creating, deleting files, you need to remove the card and re-insert for checking out the files. (The re-inserting thing is not required if you use the DevCon utility as suggested by Henry). The files which are created will contain random data, as this code is mainly to understand FAT. What is important is that windows should not display that the file is corrupt. This figure shows the results of operations we did in the last step, by opening the card in windows after re-insert:


11. Now, the next step is to see how to use the HxD Hex Editor to understand what we did in the previous steps: Install and open the HxD. From the top menu-line, under 'extras', select 'open disk', select the drive letter of the card and press OK, or select 'physical disks' & then 'removable disk1'. This will open the card memory area, starting with the first sector of the card. Here in the first sector, you can see how the boot sector or MBR (master boot record) of your card looks like.

12. Using the 'find' menu, search for the text string, the name of any file stored in the card. This will take you to the FAT (File Allocation Table) area of the card. (you need to use 'search' option, as sometimes the FAT sector will be located far away and you'll be tired of scrolling down. Alternatively, using the boot-sector data, you can manually calculate the FAT's starting sector number and directly go there by entering the sector number in the box at upper right corner). Here you can see how files are arranged in FAT, by their names, starting cluster numbers etc. Following figure shows the occupied part of FAT and shows location of 'newfile.txt', which we created in step 9.


This is really useful in understanding the effects of creation, deletion of files on FAT table & FSinfo sector, to gain a real insight of the FAT32. And this understanding helps a lot while debugging your code when you make the actual hardware.

It also helps understanding the differences in file handling by the microcontroller FAT32 code and the windows, as you can check the card data in HxD after using either of them. It'll help in debugging by bridging in the troublesome differences.

Here are the additional testing suggestions by Henry:
------------------------------------------------------------------------
In order to start debugging, you will need to enter command lines. You can either change the #if1 to #if0 in main(), or use the Visual C++ command argument input: In Visual C++, select the "Project", then "SDCard Properties", then select "Debugging", and then "Command Argunments", then enter the command. For example:" -w2 e: test1.txt".

To trace the detail of the FAT32 system, you would go to the end of the getBootSectorData() function and select "Run to Cursor". Then you would record these two important sector numbers:

unusedSectors + reservedSectorCount = starting sector of the FAT table
firstDataSector = starting sector of the data area

Now you can open the HxD hex editor to see how these two sectors and how they are being changed by the program once you start stepping through the program. You can press F10 to single step, or F11 to step into a function, or right click on a line and set a breakpoint, then press F5 to run to the breakpoint. You need to press F5 in HxD hex editor to refresh the display in order to see any changes the program made to the SD card.

Once you have master this procedure, you can try doing file transfer between Windows XP and the program, for example, writing a file in Windows XP and reading it back by the program etc. You can also use HxD hex editior to view how Windows XP changes the card when it create or delete files on the card.


Enjoy the testing, It's really a fun!!!