Search This Blog

Thursday, August 11, 2011

Serial Communication using Atmega16 : USART


USART in ATMEGA16, with VB.NET code. (Serial Port Communication)
This code is reading Voltage from ADC1 and send it on Serial port and reading the incoming serial data.
On the other hand VB.NET code will receive Serial data (Voltage) and sends a string serially 

/*****************************************************
Chip type               : ATmega16
Program type            : Application
AVR Core Clock frequency: 8.000000 MHz
Memory model            : Small
External RAM size       : 0
Data Stack size         : 256
*****************************************************/

#include
 #include
// Alphanumeric LCD Module functions
#asm
   .equ __lcd_port=0x15 ;PORTC
#endasm
#include
// Standard Input/Output functions
#include

#include
#define RXB8 1
#define TXB8 0
#define UPE 2
#define OVR 3
#define FE 4
#define UDRE 5
#define RXC 7

#define FRAMING_ERROR (1<
#define PARITY_ERROR (1<
#define DATA_OVERRUN (1<
#define DATA_REGISTER_EMPTY (1<
#define RX_COMPLETE (1<

// USART Receiver buffer
#define RX_BUFFER_SIZE 8
char rx_buffer[RX_BUFFER_SIZE];

#if RX_BUFFER_SIZE<256
unsigned char rx_wr_index,rx_rd_index,rx_counter;
#else
unsigned int rx_wr_index,rx_rd_index,rx_counter;
#endif

// This flag is set on USART Receiver buffer overflow
bit rx_buffer_overflow;

 unsigned char REC_DATA[20];  
 int J=0;


// USART Receiver interrupt service routine
interrupt [USART_RXC] void usart_rx_isr(void)
{
char status,data;
status=UCSRA;
data=UDR;

if (data == '?')
{
J=0;
//sprintf(REC_DATA," ") ;  
}
else
{
REC_DATA[J]=data;
 J++;
}

if ((status & (FRAMING_ERROR | PARITY_ERROR | DATA_OVERRUN))==0)
   {
   rx_buffer[rx_wr_index]=data;
   if (++rx_wr_index == RX_BUFFER_SIZE) rx_wr_index=0;
   if (++rx_counter == RX_BUFFER_SIZE)
      {
      rx_counter=0;
      rx_buffer_overflow=1;
      };
   };
}

#ifndef _DEBUG_TERMINAL_IO_
// Get a character from the USART Receiver buffer
#define _ALTERNATE_GETCHAR_
#pragma used+
char getchar(void)
{
char data;
//while (rx_counter==0);
data=rx_buffer[rx_rd_index];
if (++rx_rd_index == RX_BUFFER_SIZE) rx_rd_index=0;
#asm("cli")
--rx_counter;
#asm("sei")
return data;
}
#pragma used-
#endif

// USART Transmitter buffer
#define TX_BUFFER_SIZE 8
char tx_buffer[TX_BUFFER_SIZE];

#if TX_BUFFER_SIZE<256
unsigned char tx_wr_index,tx_rd_index,tx_counter;
#else
unsigned int tx_wr_index,tx_rd_index,tx_counter;
#endif

// USART Transmitter interrupt service routine
interrupt [USART_TXC] void usart_tx_isr(void)
{
if (tx_counter)
   {
   --tx_counter;
   UDR=tx_buffer[tx_rd_index];
   if (++tx_rd_index == TX_BUFFER_SIZE) tx_rd_index=0;
   };
}

#ifndef _DEBUG_TERMINAL_IO_
// Write a character to the USART Transmitter buffer
#define _ALTERNATE_PUTCHAR_
#pragma used+
void putchar(char c)
{
while (tx_counter == TX_BUFFER_SIZE);
#asm("cli")
if (tx_counter || ((UCSRA & DATA_REGISTER_EMPTY)==0))
   {
   tx_buffer[tx_wr_index]=c;
   if (++tx_wr_index == TX_BUFFER_SIZE) tx_wr_index=0;
   ++tx_counter;
   }
else
   UDR=c;
#asm("sei")
}
#pragma used-
#endif



#define ADC_VREF_TYPE 0x00

// Read the AD conversion result
unsigned int read_adc(unsigned char adc_input)
{
ADMUX=adc_input | (ADC_VREF_TYPE & 0xff);
// Delay needed for the stabilization of the ADC input voltage
delay_us(10);
// Start the AD conversion
ADCSRA|=0x40;
// Wait for the AD conversion to complete
while ((ADCSRA & 0x10)==0);
ADCSRA|=0x10;
return ADCW;
}

// Declare your global variables here

void main(void)
{
  unsigned int volt;
 unsigned char b[20];  
 int i=0;
  float f=0;
// Input/Output Ports initialization
// Port A initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTA=0x00;
DDRA=0x00;

// Port B initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTB=0x00;
DDRB=0x00;

// Port C initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTC=0x00;
DDRC=0x00;

// Port D initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTD=0x00;
DDRD=0x00;

// Timer/Counter 0 initialization
// Clock source: System Clock
// Clock value: Timer 0 Stopped
// Mode: Normal top=FFh
// OC0 output: Disconnected
TCCR0=0x00;
TCNT0=0x00;
OCR0=0x00;

// Timer/Counter 1 initialization
// Clock source: System Clock
// Clock value: Timer 1 Stopped
// Mode: Normal top=FFFFh
// OC1A output: Discon.
// OC1B output: Discon.
// Noise Canceler: Off
// Input Capture on Falling Edge
// Timer 1 Overflow Interrupt: Off
// Input Capture Interrupt: Off
// Compare A Match Interrupt: Off
// Compare B Match Interrupt: Off
TCCR1A=0x00;
TCCR1B=0x00;
TCNT1H=0x00;
TCNT1L=0x00;
ICR1H=0x00;
ICR1L=0x00;
OCR1AH=0x00;
OCR1AL=0x00;
OCR1BH=0x00;
OCR1BL=0x00;

// Timer/Counter 2 initialization
// Clock source: System Clock
// Clock value: Timer 2 Stopped
// Mode: Normal top=FFh
// OC2 output: Disconnected
ASSR=0x00;
TCCR2=0x00;
TCNT2=0x00;
OCR2=0x00;

// External Interrupt(s) initialization
// INT0: Off
// INT1: Off
// INT2: Off
MCUCR=0x00;
MCUCSR=0x00;

// Timer(s)/Counter(s) Interrupt(s) initialization
TIMSK=0x00;

// USART initialization
// Communication Parameters: 8 Data, 1 Stop, No Parity
// USART Receiver: On
// USART Transmitter: On
// USART Mode: Asynchronous
// USART Baud Rate: 9600
UCSRA=0x00;
UCSRB=0xD8;
UCSRC=0x86;
UBRRH=0x00;
UBRRL=0x33;

// Analog Comparator initialization
// Analog Comparator: Off
// Analog Comparator Input Capture by Timer/Counter 1: Off
ACSR=0x80;
SFIOR=0x00;

// ADC initialization
// ADC Clock frequency: 1000.000 kHz
// ADC Voltage Reference: AREF pin
// ADC Auto Trigger Source: None
ADMUX=ADC_VREF_TYPE & 0xff;
ADCSRA=0x83;

// LCD module initialization
lcd_init(20);

// Global enable interrupts
#asm("sei")

while (1)
      {
             ADMUX=0x21 & 0xff ;
              lcd_clear();
             lcd_gotoxy(0,0);
             delay_ms(10);    
             lcd_putsf("Volt= ");
             volt=(unsigned int) read_adc(1);
             f=volt;
             f= 5 * (f/1023);
             ftoa(f,2,b);                                 // till 4 decimal places
             sprintf(b,"%s",b) ;
             lcd_puts(b);
                 
             lcd_gotoxy(13,0);
             delay_ms(10);    
             lcd_putsf("V");
             lcd_gotoxy(0,1);
              sprintf(b," ") ;
              sprintf(b,"%u?",volt) ;
               lcd_puts(b);
                 
               for (i=0;i<20;i++)
               {
                 putchar(b[i]);
                if (b[i] =='?')
                 break;
               }
                  sprintf(b," ") ;  
                  /*
                 for (i=0;i<20;i++)
               {  
                 b[i]=getchar();
             
                 if (b[i] =='?' || b[i] =='' || b[i] ==' ')
                 break;              
               
                  delay_ms(50);    
                }
             
                  lcd_gotoxy(0,2);
                  lcd_puts(b);
                  sprintf(b," ") ;
                   */    
                 
                     lcd_gotoxy(0,2);
                     lcd_puts(REC_DATA);
                     sprintf(REC_DATA," ") ;
                   lcd_gotoxy(5,3);
                  lcd_putsf("SER COMM");
               
             
               
             delay_ms(1000);    
           

      };
}


VB.NET code

1)  Open serial Port

 If Not SerialPort1.IsOpen Then
            SerialPort1.PortName = "Com3"     'port
         
           ' Set other port parameters.
            SerialPort1.BaudRate = 9600
            SerialPort1.Parity = Parity.None
            SerialPort1.DataBits = 8
            SerialPort1.StopBits = StopBits.One
            SerialPort1.Handshake = Handshake.None
            SerialPort1.WriteBufferSize = 100000
            SerialPort1.DtrEnable = False
            SerialPort1.RtsEnable = False
            SerialPort1.Open()
       
        End If


2)  On Data_received event
 Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived

System.Threading.Thread.Sleep(100)
        'DATA_RECEIVED = DATA_RECEIVED & SerialPort1.ReadExisting()
        'DATA_RECEIVED_FLAG = 1


        Dim bRead, nRead As Integer
        Dim returnStr As String = ""
        Dim ascStr As String = ""

        bRead = SerialPort1.BytesToRead 'Number of Bytes to read
        Dim cData(bRead - 1) As Byte
        nRead = SerialPort1.Read(cData, 0, bRead)  'Reading the Data
        For Each b As Byte In cData
            DATA_RECEIVED_1 = DATA_RECEIVED_1 & " " & Chr(b)
        Next
        DATA_RECEIVED_FLAG_1 = 1
    End Sub

''There are many ways, one can choose any method.


3) Display data received and send data (On serial) (Using timer)

 Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        If DATA_RECEIVED_FLAG_1 = 1 Then
            TextBox3.Text = DATA_RECEIVED_1 & Environment.NewLine
            DATA_RECEIVED_1 = ""
            DATA_RECEIVED_FLAG_1 = 0
        End If
        If Me.CheckBox1.Checked Then
            SerialPort1.Write("VIKAS")  'String will be displayed on LCD
            System.Threading.Thread.Sleep(20)
        End If
    End Sub

       ''If CheckBox1 is checked then send data otherwise not.






Wednesday, August 10, 2011

Settings of Fuse bits and Lock bits of Atmega8535

Atmega8535 Fuse bits and Lock bits

  1)  Fuse bits
High byte :      S853SC,    WDTON,      SPIEN,         CKOPT
                      EESAVE,   BOOTSZ1,    BOOTSZ0,  BOOTRST

Low Byte:       BODLEVEL,          BODEN,         SUT1,       SUT0
                       CKSEL3,               CKSEL2,        CKSEL1,  CKSEL0

How to set Atmega8535 at 1Mhz (Internal)?  (Also Default settings of Atmega8535 )  
    High byte :    1 1 0 1 1 0 0 1             0xD9
    Low Byte:    1 1 1 0 0 0 0 1             0xE1

   In HandyProg





How to set Atmega8535 at 8Mhz (Internal)?
    High byte :    1 1 0 1 1 0 0 1             0xD9
    Low Byte:    1 1 1 0 0 1 0 0             0xE4




How to set Atmega8535 at 8Mhz (External Crystal )?
    High byte :    1 1 0 1 1 0 0 1             0xD9
    Low Byte:    1 1 1 0 1 1 11             0xEF


How to set Atmega8535 at 12-16Mhz (External Crystal )?
    High byte :    1 1 0 0 1 0 0 1             0xC9
    Low Byte:    1 1 1 0 1 1 1 1             0xEF


Lock Bits of Atmega8535 .
For HadyProg Select all six Lock Bits
For Robotics code to be written is : 0x00



Convert date and time in the desired format in vb,net


These codes help in formatting date and time in the desired format.

1.dd/MM/yyyy

String.Format("{0:dd/MM/yyyy}", DateTime.Now)

O/P = 19/12/2008

2.MM/dd/yyyy

String.Format("{0:MM/dd/yyyy}", DateTime.Now)

O/P = 12/19/2008


3.dd/MM/yy

String.Format("{0:dd/MM/yy}", DateTime.Now)

O/P = 19/12/08


4.t

String.Format("{0:t}", DateTime.Now)

O/P = 10:30 AM


5.F

String.Format("{0:F}", DateTime.Now)


o/p=Friday, December 19, 2008 10:48:46 AM

Thursday, June 23, 2011

Handle Cross(X) button on control box in form in vb.net.

 Private Sub Form1_FormClosed(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles MyBase.FormClosed
        MessageBox.Show("closed")
    End Sub
    Private Sub Form1_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        MessageBox.Show("closing")
    End Sub

Wednesday, May 11, 2011

Create a DLL in LABVIEW and Using it in VB.NET

Creating DLL in LABVIEW

Step 1: Create a New Empty Project

Step 2: Right click on My Computer icon -> New -> Vi
            New VI file will be opened.

Step 3: Add some Controls as per requirement.
            i.e   2 num controls and 1 num indicator with some mathematic control
            i.e   Addition of 2 numbers

Step 4: In the Front Panel Window, right click on the ICON below the Close button.
            Click on Show Connector.
            Again right click on that and choose the appropriate pattern.
            Now click in the box of pattern and then click on ist control,
            then click on second pattern box then click on 2nd control. Similarly connect all controls with the        pattern box.

Step 5: Save VI file and project.

Step 6: Now right click on the Build Specification in the Project explorer.
            Choose New -> Shared Library (DLL)
Step 7: Click on Information Source , Choose your VI file as Source File.
Step 8: Click on build to Create DLL

Check out other properties like naming the DLL file, how to edit source file again etc.

 Repeating these steps one can add number of VI files. VI file name will be the name of the function or sub.
------------------------------------------------------------------------

VB.NET to use DLL (built in labview)

  'protoptype   MUL_2_NOS is VI files name

    _
    Public Shared Function MUL_2_NOS(ByVal x As Double, ByVal y As Double) As Double

    End Function
or

  Declare Function MUL_2_NOS Lib "DLL PATH HERE" (ByVal x As Double, ByVal y As Double)  As    Double 

   Dim D As Double = MUL_2_NOS(2, 7)

   messagebox.show(d.tostring)

  ------------------------------------------------------------

Thursday, July 22, 2010

Atmega16 : Square wave Frequency Counter: CodeVision Code

/*****************************************************
Chip type               : ATmega16
Program type            : Application
AVR Core Clock frequency: 8.002000 MHz
Memory model            : Small
External RAM size       : 0
Data Stack size         : 256
Written By                :(Vikas Sharma)
*****************************************************/

#include
#include
#include
// Alphanumeric LCD Module functions
#asm
   .equ __lcd_port=0x15 ;PORTC
#endasm
#include
//Declare your global variables here
  unsigned char str_buffer[20];
unsigned int CNT=0;
int FLAG=0;
//Timer 1 overflow interrupt service routine
interrupt [TIM1_OVF] void timer1_ovf_isr(void)
{
       // PORTD.7=~PORTD.7;                       //High-Low pulse
       lcd_clear();
       sprintf(str_buffer,"FREQ = %u",CNT);
       lcd_puts(str_buffer);
       CNT=0;
        //TCNT1=55535;
        TCNT1=57723;
}




void main(void)
{
// Declare your local variables here

// Input/Output Ports initialization
// Port A initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTA=0x00;
DDRA=0x00;

// Port B initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTB=0xFF;
DDRB=0x00;          //input   push buttons

// Port C initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTC=0x00;
DDRC=0xff;           //output         lcd

// Port D initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTD=0x00;
DDRD=0xff;     

// Timer/Counter 0 initialization
// Clock source: System Clock
// Clock value: Timer 0 Stopped
// Mode: Normal top=FFh
// OC0 output: Disconnected
TCCR0=0x00;
TCNT0=0x00;
OCR0=0x00;

// Timer/Counter 1 initialization
// Clock source: System Clock
// Clock value: Timer1 Stopped
// Mode: Normal top=FFFFh
// OC1A output: Discon.
// OC1B output: Discon.
// Noise Canceler: Off
// Input Capture on Falling Edge
// Timer1 Overflow Interrupt: Off
// Input Capture Interrupt: Off
// Compare A Match Interrupt: Off
// Compare B Match Interrupt: Off
TCCR1A=0x00;
TCCR1B=0x00;
TCNT1H=0x00;
TCNT1L=0x00;
ICR1H=0x00;
ICR1L=0x00;
OCR1AH=0x00;
OCR1AL=0x00;
OCR1BH=0x00;
OCR1BL=0x00;

//TCNT1=55535;
 TCNT1=57723;
TCCR1A=0b00000000;
TCCR1B=0b00000101;   //SELECT CLOCK HRER CS


// Timer/Counter 2 initialization
// Clock source: System Clock
// Clock value: Timer2 Stopped
// Mode: Normal top=FFh
// OC2 output: Disconnected
ASSR=0x00;
OCR2=0x00;
TCCR2=0b00000101;
TCNT2=0xFF;

// External Interrupt(s) initialization
// INT0: Off
// INT1: Off
// INT2: Off
MCUCR=0x00;
MCUCSR=0x00;

// Timer(s)/Counter(s) Interrupt(s) initialization
TIMSK=0b00100100;                  //6 bit timer2  0 bit tiemr0   2 bit timer1 

// Analog Comparator initialization
// Analog Comparator: Off
// Analog Comparator Input Capture by Timer/Counter 1: Off
ACSR=0x80;
SFIOR=0x00;
#asm("sei")

lcd_init(20);
lcd_putsf("FREQ-");
while (1)
      {
      // Place your code here
           if (PINB.4 == 0 && FLAG==0)
            {
                CNT=CNT+1;
                FLAG=1; 
            }
             if (PINB.4 == 1)
             {
                FLAG=0;
             }
      //PORTD.0=PINB.4;
     // delay_ms(1000);

      };
}

Wednesday, May 12, 2010

VB.NET CODE USING GRIDVIEW AND ACCESS DATABASE

Imports System.Data
Imports System.Data.OleDb

Public Class MAIN
    Public connString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=GAURAV_DATABASE.mdb"
    Public OleDBConn1 As System.Data.OleDb.OleDbConnection = New System.Data.OleDb.OleDbConnection(connString)
    Public SQLString As String
    Public OleDbDataAdapter1 As New OleDbDataAdapter()
    Public DataSet1 As New DataSet()
    Public cb As New OleDb.OleDbCommandBuilder()
    'myConnection = new SqlConnection("server=(local)\VSdotNET;Trusted_Connection=yes;database=northwind")
    ' da = new SqlDataAdapter("Select * from Customers", thisConnection)
    'Public thisConnection As New SqlConnection("server=(local);Trusted_Connection=yes;database=GAURAV_DATABASE.mdb")
    'Public cb As New SqlCommandBuilder()
    'Public da As New SqlDataAdapter()
    'Public SqlCommand1 As New SqlCommand()
    '' Sql Query
    'Public sql As String = "SELECT * FROM IMPORTANT"
    '' Create a Command
    '' Create SqlDataAdapter
    ''da = New SqlDataAdapter
    ''da.SelectCommand = SqlCommand1

    Private Sub BTN_EXIT_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BTN_EXIT.Click
        login.Close()
        Me.Close()
    End Sub

    Private Sub MAIN_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        'If InputBox("ENTER PASSWORD:", "GAURAV DETAILS", "**********") <> "vikas" Then
        '    MessageBox.Show("INCORRECT PASSWORD!!!!!!!", "GAURAV DETAILS", MessageBoxButtons.OK, MessageBoxIcon.Error)
        '    Me.Close()
        'End If
        'Dim myConnection As OleDbConnection = New OleDbConnection
        'myConnection.ConnectionString = connString
        '' create a data adapter
        'Dim da As OleDbDataAdapter = New OleDbDataAdapter("Select * from IMPORTANT", myConnection)

        'Dim ds As DataSet = New DataSet
        'da.Fill(ds, "Customers")
        'DATA_GRID.DataSource = ds.DefaultViewManager
        '  Dim ConnString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=MyMDB.mdb"
        '  OleDBConn1.Open()
    End Sub

    Private Sub BTN_IMPORTANT_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BTN_IMPORTANT.Click
        DataSet1.Clear()
        SQLString = "SELECT * FROM IMPORTANT"
        OleDbDataAdapter1 = New OleDbDataAdapter(SQLString, OleDBConn1)
        'OleDBConn1.Open()
        OleDbDataAdapter1.Fill(DataSet1, "IMPORTANT")
        DATA_GRID.DataSource = DataSet1.Tables("IMPORTANT")
        'OleDBConn1.Close()
        cb = New OleDb.OleDbCommandBuilder(OleDbDataAdapter1)

        'Dim sql As String = "SELECT * FROM IMPORTANT"
        'SqlCommand1 = New SqlCommand(sql, thisConnection)
        'da = New SqlDataAdapter
        'da.SelectCommand = SqlCommand1
        'cb = New SqlCommandBuilder(da)
        'da.Fill(DataSet1, "IMPORTANT")
        'DATA_GRID.DataSource = DataSet1.Tables("IMPORTANT")
        'DATA_GRID.SetDataBinding(DataSet1, "IMPORTANT")
        'Try
        '    da = New SqlDataAdapter("select * from IMPORTANT", thisConnection)
        '    'da.SelectCommand = New SqlCommand()
        '    'da.SelectCommand.Connection = thisConnection
        '    'da.SelectCommand.CommandText = "select * from IMPORTANT"
        '    'da.SelectCommand.CommandType = CommandType.Text
        '    thisConnection.Open()
        '    cb = New SqlCommandBuilder(da)
        '    ' Set the MissingSchemaAction property to AddWithKey because Fill will not cause primary
        '    ' key & unique key information to be retrieved unless AddWithKey is specified.
        '    da.MissingSchemaAction = MissingSchemaAction.AddWithKey
        '    da.Fill(DataSet1, "IMPORTANT")
        '    DATA_GRID.DataSource = DataSet1.Tables("IMPORTANT")
        '    'DATA_GRID.AutoGenerateColumns = True
        '    'DATA_GRID.DataSource = DataSet1
        '    'DATA_GRID.DataMember = "IMPORTANT"
        '    thisConnection.Close()
        'Catch ex As Exception
        '    MessageBox.Show(ex.ToString)
        'End Try
    End Sub

    Private Sub BTN_INVESTMENT_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BTN_INVESTMENT.Click
        DataSet1.Clear()
        SQLString = "SELECT * FROM INVESTMENTS"
        OleDbDataAdapter1 = New OleDbDataAdapter(SQLString, OleDBConn1)
        'OleDBConn1.Open()
        OleDbDataAdapter1.Fill(DataSet1, "INVESTMENTS")
        DATA_GRID.DataSource = DataSet1.Tables("INVESTMENTS")
        cb = New OleDb.OleDbCommandBuilder(OleDbDataAdapter1)
        ' OleDBConn1.Close()
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Try
            '   Dim cb As New OleDb.OleDbCommandBuilder(OleDbDataAdapter1)
            ' DataSet1.Tables("IMPORTANT").Rows(0).Item(1) = "vvvvvvvvv"
            'DataSet1.Tables("IMPORTANT").Rows(0).Item(2) = "99999999"
           
            OleDbDataAdapter1.Update(DataSet1, DATA_GRID.DataSource.ToString)
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
        MessageBox.Show("UPDATE " & DATA_GRID.DataSource.ToString & " DATABASE")


        'SQLString = "UPDATE TABLE INVESTMENTS"
        'OleDbDataAdapter1 = New OleDbDataAdapter(SQLString, OleDBConn1)
        'OleDBConn1.Open()

        'DATA_GRID.DataSource = DataSet1.Tables(0)
        'MessageBox.Show(DataSet1.Tables(1).ToString)
        ' DATA_GRID.DataSource = DataSet1.Tables("IMPORTANT")
        ' OleDbDataAdapter1.Update(DataSet1)
        ' OleDbDataAdapter1.InsertCommand = New OleDbCommand("Insert into IMPORTANT (ID,NAME,PH) VALUES()", OleDBConn1)
        ' OleDbDataAdapter1 = New OleDbDataAdapter(SQLString, OleDBConn1)
        ' OleDbDataAdapter1.Update(DataSet1)
        'DATA_GRID.DataSource = DataSet1.Tables(" IMPORTANT")
        'OleDBConn1.Close()
    End Sub

    Private Sub BTN_REMINDERS_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BTN_REMINDERS.Click
        DataSet1.Clear()
        SQLString = "SELECT * FROM REMINDERS"
        OleDbDataAdapter1 = New OleDbDataAdapter(SQLString, OleDBConn1)
        'OleDBConn1.Open()
        OleDbDataAdapter1.Fill(DataSet1, "REMINDERS")
        DATA_GRID.DataSource = DataSet1.Tables("REMINDERS")
        cb = New OleDb.OleDbCommandBuilder(OleDbDataAdapter1)
    End Sub

    Private Sub BTN_VAULT_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BTN_VAULT.Click
        DataSet1.Clear()
        SQLString = "SELECT * FROM VAULT"
        OleDbDataAdapter1 = New OleDbDataAdapter(SQLString, OleDBConn1)
        'OleDBConn1.Open()
        OleDbDataAdapter1.Fill(DataSet1, "VAULT")
        DATA_GRID.DataSource = DataSet1.Tables("VAULT")
        cb = New OleDb.OleDbCommandBuilder(OleDbDataAdapter1)
    End Sub

    Private Sub BTN_BANKING_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BTN_BANKING.Click
        DataSet1.Clear()
        SQLString = "SELECT * FROM BANKING"
        OleDbDataAdapter1 = New OleDbDataAdapter(SQLString, OleDBConn1)
        'OleDBConn1.Open()
        OleDbDataAdapter1.Fill(DataSet1, "BANKING")
        DATA_GRID.DataSource = DataSet1.Tables("BANKING")
        cb = New OleDb.OleDbCommandBuilder(OleDbDataAdapter1)
    End Sub

    Private Sub BTN_PLANS_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BTN_PLANS.Click
        DataSet1.Clear()
        SQLString = "SELECT * FROM PLANS"
        OleDbDataAdapter1 = New OleDbDataAdapter(SQLString, OleDBConn1)
        'OleDBConn1.Open()
        OleDbDataAdapter1.Fill(DataSet1, "PLANS")
        DATA_GRID.DataSource = DataSet1.Tables("PLANS")
        cb = New OleDb.OleDbCommandBuilder(OleDbDataAdapter1)
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        DataSet1.Clear()
        SQLString = "SELECT * FROM CONTACTS"
        OleDbDataAdapter1 = New OleDbDataAdapter(SQLString, OleDBConn1)
        'OleDBConn1.Open()
        OleDbDataAdapter1.Fill(DataSet1, "CONTACTS")
        DATA_GRID.DataSource = DataSet1.Tables("CONTACTS")
        cb = New OleDb.OleDbCommandBuilder(OleDbDataAdapter1)
    End Sub
End Class

Tuesday, May 11, 2010

Singly Link List : C code

#includestdio.h
#includeconio.h
#includealloc.h
#includestdlib.h
struct s_ll
{
 int x;
 struct s_ll *nxt;

} *ll;

void append(struct s_ll **, int);
void in_begin(struct s_ll **, int);
void del(struct s_ll **, int);
void in_middle(struct s_ll **, int, int);
int count(struct s_ll *);
void display(struct s_ll *);

void main()
{
 int i=2;
 int j=2;
 int ch,num,loc;

 ll=NULL;
 clrscr();
 printf("PRESS ENTER ");

 getch();
 clrscr();
 for(i=1;i<20;i++)
 {
 gotoxy(i,j);
  printf("*");
  j++;

 }
  for(;i<39;i++)
 {
 j--;
 gotoxy(i,j);
 printf("*");

 }
     getch();
 clrscr();

  gotoxy(0,0);
  printf("****** MAIN MENU ***********\n");
  printf("1. READ A FILE\n");
  printf("2. WRITE A FILE\n");
  printf("3. XXXXXXXXXXXXX\n");
  printf("4. YYYYYYYYYYYYY\n");
  printf("****************************\n");



 getch();


 do
 {
  clrscr();
  gotoxy(0,0);
  printf("******** PROGRAM TO IMPLEMENT SINGLY nxt LIST ***********\n");
  printf("-----------------------------------------------------------\n");
  printf("1. CREATE OR APPEND\n");
  printf("2. INSERT AT START\n");
  printf("3. INSERT AT MIDDLE\n");
  printf("4. DELETE A NODE\n");
  printf("5. COUNT NODE\n");
  printf("6. DISPLAY NODE\n");
  printf("7. EXIT\n");
  printf("***********************************************************\n");

  oper:
  printf("ENTER CHOICE (1-6)/7 FOR EXIT - ");
  scanf("%d",&ch);

 switch(ch)
 {
   case 1:
    char res;
    do {
      printf("ENTER ANY NUMBER : ");
      scanf("%d",&num);
      append(&ll,num);
      printf("ENTER AGAIN (y/n) : ");
      fflush(stdin);
      res=getchar();

    } while(res != 'n');
    break;
case 2:
printf("Enter The x : ");
scanf("%d",&num);
in_begin(&ll,num);
break;
case 3:
printf("\nEnter The Position :");
scanf("%d",&loc);
printf("\nEnter The x : ");
scanf("%d",&num);
in_middle(&ll,loc,num);
break;
case 4:
printf("\nEnter The x u Want To Delete : ");
scanf("%d",&num);
del(&ll,num);
break;
case 5:
printf("\nThe No Of s_lls Are %d",count(ll));
getch();
break;
case 6:
display(ll);
getch();
break;
case 7:
printf("\n\nQuiting.......");
getch();
exit(0);
break;
default:
printf("Invalid choice.Please Enter Correct Choice");
//goto oper;
 }

 }while(ch != 7);



}

void append(struct s_ll **q,int num)
{ struct s_ll *temp,*r;
temp = *q;
if(*q==NULL)
{ temp = (struct s_ll *)malloc(sizeof(struct s_ll));
temp->x=num;
temp->nxt=NULL;
*q=temp;
}
else
{ temp = *q;
while(temp->nxt !=NULL)
{ temp=temp->nxt;
}
r = (struct s_ll *)malloc(sizeof(struct s_ll));
r->x=num;
r->nxt=NULL;
temp->nxt=r;
}
}
void display(struct s_ll *q)
{ if(q==NULL)
{ printf("\n\nEmpty nxt List.Can't Display The x");
getch();
goto last;
}
while(q!=NULL)
{ printf("\n%d",q->x);
q=q->nxt;
}
last:
}

int count(struct s_ll *q)
{ int c=0;
if(q==NULL)
{ printf("Empty nxt List.\n");
getch();
goto last;
}
while(q!=NULL)
{ c++;
q=q->nxt;
}
last:
return c;
}

void in_begin(struct s_ll **q,int num)
{ struct s_ll *temp;
if(*q==NULL)
{ printf("nxt List Is Empty.Can't Insert.");
getch();
goto last;
}
else
{ temp=(struct s_ll *)malloc(sizeof(struct s_ll));
temp->x=num;
temp->nxt=*q;
*q=temp; /* pointing to the first s_ll */
}
last:
getch();
}

void in_middle(struct s_ll **q,int loc,int num)
{ struct s_ll *temp,*n;
int c=1,flag=0;
temp=*q;
if(*q==NULL)
{ printf("\n\nnxt List Is Empty.Can't Insert.");
getch();
goto last;
}
else
while(temp!=NULL)
{ if(c==loc)
{ n = (struct s_ll *)malloc(sizeof(struct s_ll));
n->x=num;
n->nxt=temp->nxt;
temp->nxt=n;
flag=1;
}
c++;
temp=temp->nxt;
}
if(flag==0)
{ printf("\n\ns_ll Specified Doesn't Exist.Cant Enter The x");
getch();
}
else
{ printf("x Inserted");
getch();
}
last:
getch();
}
void del(struct s_ll**q,int num)
{ if(*q==NULL)
{ printf("\n\nEmpty nxted List.Cant Delete The x.");
getch();
goto last;
}
else
{
struct s_ll *old,*temp;
int flag=0;
temp=*q;
while(temp!=NULL)
{ if(temp->x==num)
{ if(temp==*q) /* First s_ll case */
*q=temp->nxt; /* shifted the header s_ll */
else
old->nxt=temp->nxt;
free(temp);
flag=1;
}
else
{ old=temp;
temp=temp->nxt;
}
}
if(flag==0)
printf("\nx Not Found...");
else
printf("\nx Deleted...Tap a key to continue");
getch();
}
last:
getch();
}

Monday, April 19, 2010

A SQUARE WAVE WITH 1.2 MICOR SEC DELAY, USING TIMER CVAVR ATMEGA16

/*****************************************************
This program was produced by the
CodeWizardAVR V2.03.9 Standard
Automatic Program Generator


© Copyright 1998-2008 Pavel Haiduc, HP InfoTech s.r.l.
http://www.hpinfotech.com

Project :
Version :
Date    : 05-04-2010
Author  : VIKAS
Company : ETM
Comments:


Chip type               : ATmega16
Program type            : Application
AVR Core Clock frequency: 8.000000 MHz
Memory model            : Small
External RAM size       : 0
Data Stack size         : 256
*****************************************************/

#include
#include


interrupt [TIM0_OVF] void timer0_ovf_isr(void)
{
     //PORTC.3=0;
     #asm("CBI  0x15,3")  
     TCCR0=0b00000000;
     TCNT0=205;
}
// Declare your global variables here

void main(void)
{
// Declare your local variables here
  // unsigned int BTN_H=0;
// Input/Output Ports initialization
// Port A initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTA=0x00;
DDRA=0x00;

// Port B initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTB=0xFF;
DDRB=0x00;

// Port C initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTC=0x00;
DDRC=0x00;

DDRC.3=1;  //output

DDRC.2=0;   //input
PORTC.2=1;
// Port D initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTD=0x00;
DDRD=0xff;  

// Timer/Counter 0 initialization
// Clock source: T0 pin Falling Edge
// Mode: Normal top=FFh
// OC0 output: Disconnected
//TCCR0=0x06;
TCCR0=0b00000000;                   //0b00000101;
TCNT0=205;  
OCR0=0x00;

// Timer/Counter 1 initialization
// Clock source: System Clock
// Clock value: Timer 1 Stopped
// Mode: Normal top=FFFFh
// OC1A output: Discon.
// OC1B output: Discon.
// Noise Canceler: Off
// Input Capture on Falling Edge
// Timer 1 Overflow Interrupt: Off
// Input Capture Interrupt: Off
// Compare A Match Interrupt: Off
// Compare B Match Interrupt: Off
ICR1H=0x00;
ICR1L=0x00;
OCR1AH=0x00;
OCR1AL=0x00;
OCR1BH=0x00;
OCR1BL=0x00;
TCNT1=65535;
TCCR1A=0b00000000;
TCCR1B=0b00000000;   //SELECT CLOCK HRER CS

// Timer/Counter 2 initialization
// Clock source: System Clock
// Clock value: Timer 2 Stopped
// Mode: Normal top=FFh
// OC2 output: Disconnected
ASSR=0x00;
TCCR2=0x00;
TCNT2=0x00;
OCR2=0x00;

// External Interrupt(s) initialization
// INT0: Off
// INT1: Off
// INT2: Off
MCUCR=0x00;
MCUCSR=0x00;

// Timer(s)/Counter(s) Interrupt(s) initialization
TIMSK=0b00000001;                  //6 bit timer2  0 bit tiemr0   2 bit timer1 

#asm("sei")
// Analog Comparator initialization
// Analog Comparator: Off
// Analog Comparator Input Capture by Timer/Counter 1: Off
ACSR=0x80;
SFIOR=0x00;

while (1)
      {        
       
      if (PINC.2==0)
      {
       //TCCR0=0b00000001;
       //PORTC.3=1;
       #asm ("SBI 0x15,3")   
       #asm("nop")
       #asm("nop")
       #asm("nop")
       #asm("nop")
       #asm("nop")
       #asm("nop")
       #asm("nop")
       #asm("nop")
       #asm("CBI  0x15,3") 
      //  BTN_H=1;
        delay_ms(2000);
      }        
      
        
     //if (PINC.2==1)      
     //  BTN_H=0;
     
     
      /*
       
        if (PINC.2==0 && BTN_H==0)
          {
            PORTC.3=1;
            delay_ms(8000);
                                                PORTC.3=0;
          }
       
         if (PINC.2==1)      
       BTN_H=0;
        */
      
      
      };
}

READ ADC VOLTAGE 0-255 FROM PORTA PIN A-0,A-1 CVAVR ATMEGA16

/*****************************************************
This program was produced by the
CodeWizardAVR V2.03.9 Standard
Automatic Program Generator
© Copyright 1998-2008 Pavel Haiduc, HP InfoTech s.r.l.
http://www.hpinfotech.com

Project : two_adc
Version :
Date    : 19-04-2010
Author  : Vikas Sharma
Company : ETM
Comments:


Chip type               : ATmega16
Program type            : Application
AVR Core Clock frequency: 8.000000 MHz
Memory model            : Small
External RAM size       : 0
Data Stack size         : 256
*****************************************************/

#include

// Alphanumeric LCD Module functions
#asm
   .equ __lcd_port=0x15 ;PORTC
#endasm
#include

#include
#include

#define ADC_VREF_TYPE 0x20

// Read the 8 most significant bits of the AD conversion result
unsigned char read_adc(unsigned char adc_input)
{
    ADMUX=adc_input | (ADC_VREF_TYPE & 0xff);
    // Delay needed for the stabilization of the ADC input voltage
    delay_us(10);
    // Start the AD conversion
    ADCSRA|=0x40;
    // Wait for the AD conversion to complete
    while ((ADCSRA & 0x10)==0);
    ADCSRA|=0x10;
    return ADCH;
}

// Declare your global variables here

void main(void)
{
// Declare your local variables here
 unsigned int volt, volt1;
 unsigned char b[20];
// Input/Output Ports initialization
// Port A initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTA=0x00;
DDRA=0x00;

// Port B initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTB=0xFF;
DDRB=0x00;

// Port C initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTC=0x00;
DDRC=0xFF;

// Port D initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTD=0x00;
DDRD=0xFF;

// Timer/Counter 0 initialization
// Clock source: System Clock
// Clock value: Timer 0 Stopped
// Mode: Normal top=FFh
// OC0 output: Disconnected
TCCR0=0x00;
TCNT0=0x00;
OCR0=0x00;

// Timer/Counter 1 initialization
// Clock source: System Clock
// Clock value: Timer 1 Stopped
// Mode: Normal top=FFFFh
// OC1A output: Discon.
// OC1B output: Discon.
// Noise Canceler: Off
// Input Capture on Falling Edge
// Timer 1 Overflow Interrupt: Off
// Input Capture Interrupt: Off
// Compare A Match Interrupt: Off
// Compare B Match Interrupt: Off
TCCR1A=0x00;
TCCR1B=0x00;
TCNT1H=0x00;
TCNT1L=0x00;
ICR1H=0x00;
ICR1L=0x00;
OCR1AH=0x00;
OCR1AL=0x00;
OCR1BH=0x00;
OCR1BL=0x00;

// Timer/Counter 2 initialization
// Clock source: System Clock
// Clock value: Timer 2 Stopped
// Mode: Normal top=FFh
// OC2 output: Disconnected
ASSR=0x00;
TCCR2=0x00;
TCNT2=0x00;
OCR2=0x00;

// External Interrupt(s) initialization
// INT0: Off
// INT1: Off
// INT2: Off
MCUCR=0x00;
MCUCSR=0x00;

// Timer(s)/Counter(s) Interrupt(s) initialization
TIMSK=0x00;

// Analog Comparator initialization
// Analog Comparator: Off
// Analog Comparator Input Capture by Timer/Counter 1: Off
ACSR=0x80;
SFIOR=0x00;

// ADC initialization
// ADC Clock frequency: 1000.000 kHz
// ADC Voltage Reference: AREF pin
// ADC Auto Trigger Source: None
ADMUX=ADC_VREF_TYPE & 0xff;
ADCSRA=0xA6;
SFIOR&=0x1F;

// LCD module initialization
lcd_init(20);


while (1)
      {
      // Place your code here   
             ADMUX=0x20 & 0xff ;                      //SET PIN  PORTA.0
             delay_ms(10);
             volt=(unsigned int) read_adc(0);
             lcd_gotoxy(0,0);
             sprintf(b,"%u  ",volt)  ;
             lcd_puts(b); 
             delay_ms(100);
            
             ADMUX=0x21 & 0xff;                             //SET PIN  PORTA.1
             delay_ms(10);
             volt1=(unsigned int) read_adc(1);                       
            
          //ADMUX=0x22 & 0xff;                             //SET PIN  PORTA.2            AND SO......ON.......


       
                                                  lcd_gotoxy(0,1);
           sprintf(b,"%u  ",volt1)  ;
                     lcd_puts(b); 
           
           lcd_gotoxy(0,2);
            lcd_putsf("VIKAS");
           
          lcd_gotoxy(0,3);
          lcd_putsf("VIKAS");
            delay_ms(100);
      };
}

Wednesday, March 31, 2010

Atmega16 code Timer example, using external oscilator, watchdog timer

/*****************************************************
Chip type               : ATmega16
Program type            : Application
AVR Core Clock frequency: 16.000000 MHz External Crystal
Memory model            : Small
External RAM size       : 0
Data Stack size         : 256
*****************************************************/

#include mega16.h
#include delay.h
#include stdio.h
// Alphanumeric LCD Module functions
#asm
   .equ __lcd_port=0x15 ;PORTC
#endasm
#include lcd.h>
#define ADC_VREF_TYPE 0x20

// Read the 8 most significant bits of the AD conversion result
unsigned char read_adc(unsigned char adc_input)
{
    ADMUX=adc_input | (ADC_VREF_TYPE & 0xff);
    // Delay needed for the stabilization of the ADC input voltage
    delay_us(10);
    // Start the AD conversion
    ADCSRA|=0x40;
    // Wait for the AD conversion to complete
    while ((ADCSRA & 0x10)==0);
    ADCSRA|=0x10;
    return ADCH;
}

// global variables
//unsigned int freq_array[]={50,100,150,200,250,300,350,400,450,500,550,600,650,700,750,800,850,900,950,1000} ;
//unsigned int no_of_pulses[]={2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40} ;
//unsigned int pc_array[]={1,2,5,10,20,50,100,200,500,1000} ;
void PC_OUTPUTS(void);
void DELAY(void);
void CODE(void);
void ADC_DELAY(unsigned int);

unsigned int actual_delay_time,volt;
unsigned int FREQ_COUNTER=2;
unsigned int PC_COUNTER=1;
unsigned int var=1;
unsigned int var2=1;
unsigned int BTN_0=0;      
unsigned int BTN_1=0;
unsigned int BTN_2=0;
unsigned int BTN_3=0;
unsigned int BTN_4=0;
unsigned int S_10=0;
unsigned int ON_OFF_FLAG=0;       //CAL ON/OFF flag

//EEPROM VARS
#pragma warn-
eeprom unsigned int EE_FREQ_COUNTER=2 ;
eeprom unsigned int EE_PC_COUNTER=1 ;
unsigned int eeprom *ptr_EE_FREQ_COUNTER;
unsigned int eeprom *ptr_EE_PC_COUNTER;
#pragma warn+
unsigned int  *ptr_FREQ_COUNTER,*ptr_PC_COUNTER;

//Timer 1 overflow interrupt service routine
interrupt [TIM1_OVF] void timer1_ovf_isr(void)
{
        PORTD.7=~PORTD.7;                       //High-Low pulse
        TCNT1=actual_delay_time;
}

interrupt [TIM0_OVF] void timer0_ovf_isr(void)
{
   var++;                    //Approx. 10 sec delay
   if (var > 10000)
   {    
      var=1; 
      S_10++;    
   }        
   if(S_10 == 10)
    {
      PORTD.2=0;                       //High-Low pulse
      S_10=0;
      TCCR0=0b00000000;
    }
   TCNT0=0xFF;
}

interrupt [TIM2_OVF] void timer2_ovf_isr(void)
{
   var2++;         //Push buttons delay
   if (var2 > 54000)
   {  
        var2=1;
        BTN_0=0;      
        BTN_1=0;
        BTN_2=0;
        BTN_3=0;
        BTN_4=0;
   }
    TCNT2=0xFF;     
}

void main(void)
{
// Input/Output Ports initialization
// Port A initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTA=0x00;
DDRA=0x00;

// Port B initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTB=0xFF;
DDRB=0x00;          //input   push buttons

// Port C initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTC=0x00;
DDRC=0xff;           //output         lcd

// Port D initialization
// Func7=In Func6=In Func5=In Func4=In Func3=In Func2=In Func1=In Func0=In
// State7=T State6=T State5=T State4=T State3=T State2=T State1=T State0=T
PORTD=0x00;
DDRD=0xff;           //output     led

DDRD.3=0;
PORTD.3=1;

// Timer/Counter 0 initialization
// Clock source: System Clock
// Clock value: Timer 0 Stopped
// Mode: Normal top=FFh
// OC0 output: Disconnected
TCCR0=0b00000000;                   //0b00000101;
TCNT0=0xFF;
OCR0=0x00;

// Timer/Counter 1 initialization
// Clock source: System Clock
// Clock value: Timer1 Stopped
// Mode: Normal top=FFFFh
// OC1A output: Discon.
// OC1B output: Discon.
// Noise Canceler: Off
// Input Capture on Falling Edge
// Timer1 Overflow Interrupt: Off
// Input Capture Interrupt: Off
// Compare A Match Interrupt: Off
// Compare B Match Interrupt: Off
ICR1H=0x00;
ICR1L=0x00;
OCR1AH=0x00;
OCR1AL=0x00;
OCR1BH=0x00;
OCR1BL=0x00;
TCNT1=55535;
TCCR1A=0b00000000;
TCCR1B=0b00000010;   //SELECT CLOCK HRER CS
       
// Timer/Counter 2 initialization
// Clock source: System Clock
// Clock value: Timer2 Stopped
// Mode: Normal top=FFh
// OC2 output: Disconnected
ASSR=0x00;
OCR2=0x00;
TCCR2=0b00000101;
TCNT2=0xFF;

// External Interrupt(s) initialization
// INT0: Off
// INT1: Off
// INT2: Off
MCUCR=0x00;
MCUCSR=0x00;

//Timer(s)/Counter(s) Interrupt(s) initialization
//TIMSK=0x00;
TIMSK=0b01000101;                  //6 bit timer2  0 bit tiemr0   2 bit timer1 
// Analog Comparator initialization
// Analog Comparator:
// Analog Comparator Input Capture by Timer/Counter 1: Off
ACSR=0x80;
SFIOR=0x00;
ADMUX=ADC_VREF_TYPE & 0xff;
ADCSRA=0xA6;
SFIOR&=0x1F;

lcd_init(20);
lcd_clear();
lcd_putsf("ETM");

ptr_EE_FREQ_COUNTER=&EE_FREQ_COUNTER;
ptr_EE_PC_COUNTER=&EE_PC_COUNTER;
ptr_FREQ_COUNTER=&FREQ_COUNTER;
ptr_PC_COUNTER=&PC_COUNTER;
*ptr_FREQ_COUNTER=*ptr_EE_FREQ_COUNTER;
*ptr_PC_COUNTER=*ptr_EE_PC_COUNTER;

#asm("sei")
DELAY();
PC_OUTPUTS();

// Watchdog Timer initialization
// Watchdog Timer Prescaler: OSC/256k
#pragma optsize-
WDTCR=0x1C;
WDTCR=0b00001111;
#ifdef _OPTIMIZE_SIZE_
#pragma optsize+
#endif

PORTD.7=0;
TCCR1A=0b00000000;
TCCR1B=0b00000000;       //STOP TIMER
lcd_gotoxy(13,1);
lcd_putsf("OFF");
               
while (1)
      { 
         //read voltage from PORTA.0  0 - 255   
         WDTCR=0b00001111;
         volt=(unsigned int)read_adc(0);                                 //100 us 
         if (S_10==0)
         {     
             if(PIND.3==0)
             {
              PORTD.2=1;
              S_10=1;
              TCCR0=0b00000101;
             }
         }      
        DELAY();  
        WDTCR=0b00001111;          
        CODE(); 
        delay_ms(350);       
      };                                                        //END OF WHILE LOOP              
}                                                               //END OF MAIN

void CODE()
{
        //CAL ON OFF
        if (PINB.4 == 0 && BTN_4==0)
         {
            if (ON_OFF_FLAG==1) 
            {
                ON_OFF_FLAG=0;
                lcd_gotoxy(13,1);
                lcd_putsf("OFF");  
                PORTD.7=0;
                TCCR1A=0b00000000;
                TCCR1B=0b00000000;   //STOP TIMER 
            }   
            else
            {
                ON_OFF_FLAG=1; 
                lcd_gotoxy(13,1);
                lcd_putsf(" ON"); 
                PC_OUTPUTS();  
                TCCR1A=0b00000000;
                TCCR1B=0b00000010;   //START TIMER           prescaler=8 
                //PORTD.2=1;
                //TCCR0=0b00000101;
            }
            BTN_4=1;
         }
         if (PINB.4 == 1)
            BTN_4=0;              
                   
        //INCREASE NO OF PULSES PORTB 0 PIN       
        if (PINB.0 == 0 && BTN_0==0)
         {
            if (FREQ_COUNTER < 40)
             {
              FREQ_COUNTER=FREQ_COUNTER+2; 
              *ptr_EE_FREQ_COUNTER=*ptr_FREQ_COUNTER;
             }  
             else
             {
              FREQ_COUNTER=2;
              *ptr_EE_FREQ_COUNTER=*ptr_FREQ_COUNTER;
             }
             BTN_0=1; 
         }
        if (PINB.0 == 1)
            BTN_0=0;       
        
        //DECREASE NO OF PULSES PORTB 1 PIN     
        if (PINB.1 == 0 && BTN_1==0)
         {    
            if (FREQ_COUNTER > 2)
             {
                FREQ_COUNTER=FREQ_COUNTER - 2;  
               *ptr_EE_FREQ_COUNTER=*ptr_FREQ_COUNTER;
             }
             else
             {
               FREQ_COUNTER=40;  
               *ptr_EE_FREQ_COUNTER=*ptr_FREQ_COUNTER;
             }
             BTN_1=1; 
         } 
        if (PINB.1 == 1)
            BTN_1=0;       
             
        //INCREASE IN PC COUNT PORTB 2 PIN     
        if (PINB.3 == 0 && BTN_2==0)
         {
            if (PC_COUNTER < 10)
             {      
                PC_COUNTER++;
                PC_OUTPUTS();
               *ptr_EE_PC_COUNTER=*ptr_PC_COUNTER;
             }
             else
             {
                PC_COUNTER=1;
                PC_OUTPUTS();
               *ptr_EE_PC_COUNTER=*ptr_PC_COUNTER;            
             }
             BTN_2=1;
         }
        if (PINB.3 == 1)
            BTN_2=0;       
          
        //DECREAE IN PC COUNT PORTB 2 PIN     
        if (PINB.2 == 0 && BTN_3 == 0)
         {
            if (PC_COUNTER > 1)
             {
                PC_COUNTER--;
                PC_OUTPUTS();
                *ptr_EE_PC_COUNTER=*ptr_PC_COUNTER;
             }
             else
             {
                PC_COUNTER=10;
                PC_OUTPUTS();
                *ptr_EE_PC_COUNTER=*ptr_PC_COUNTER;
             }
             BTN_3=1;  
         }
        
        if (PINB.2 == 1)
            BTN_3=0;       
      
        //BATTERY INDICATION  PORTB 5 PIN - LO   6 - OK  7 - CH
        if (PINB.6 == 0)
         {
            lcd_gotoxy(10,0);
            lcd_putsf("BAT OK");
         }
         else if (PINB.7 == 0)
         {
            lcd_gotoxy(10,0);
            lcd_putsf("BAT CH");
         }  
         else if  (PINB.5 == 0)
         {
            lcd_gotoxy(10,0);
            lcd_putsf("BAT LO");
         }
         else
         { 
            lcd_gotoxy(10,0);
            lcd_putsf("      ");   
         }
}

/*------------------------------------------------------------------------------
 Procedure:    PC_OUTPUTS
 Inputs:        none
 Return:        none
 Description:    Vary the 5 PC signals
------------------------------------------------------------------------------*/

void PC_OUTPUTS(void)
{
       lcd_gotoxy(0,1);
       switch (PC_COUNTER)
       {
         case 1:      
             PORTD.0=0;
             PORTD.1=0;
             PORTD.4=1;  
             PORTD.5=0;
             PORTD.6=1;
             //lcd_gotoxy(0,1);
             lcd_putsf("CAL PC 1   ");
             break;  
         case 2: 
             PORTD.0=0;
             PORTD.1=1;
             PORTD.4=0;  
             PORTD.5=1;
             PORTD.6=0;
             //lcd_gotoxy(0,1);
               lcd_putsf("CAL PC 2  ");
             break;
         case 3:
             PORTD.0=1;
             PORTD.1=0;
             PORTD.4=1;  
             PORTD.5=1;
             PORTD.6=0;
             //lcd_gotoxy(0,1);
               lcd_putsf("CAL PC 5   ");
             break;
         case 4:
             PORTD.0=0;
             PORTD.1=0;
             PORTD.4=1;  
             PORTD.5=1;
             PORTD.6=0;
             //lcd_gotoxy(0,1);
               lcd_putsf("CAL PC 10  ");
             break;
         case 5:
             PORTD.0=0;
             PORTD.1=1;
             PORTD.4=1;  
             PORTD.5=0;
             PORTD.6=0;
             //lcd_gotoxy(0,1);
             lcd_putsf("CAL PC 20  ");
             break;   
          case 6:      
             PORTD.0=1;
             PORTD.1=0;
             PORTD.4=1;  
             PORTD.5=0;
             PORTD.6=0; 
             //lcd_gotoxy(0,1);
              lcd_putsf("CAL PC 50  ");
             break;  
         case 7: 
             PORTD.0=0;
             PORTD.1=0;
             PORTD.4=1;  
             PORTD.5=0;
             PORTD.6=0;
             //lcd_gotoxy(0,1);
              lcd_putsf("CAL PC 100 ");
             break;
         case 8:
             PORTD.0=0;
             PORTD.1=1;
             PORTD.4=0;  
             PORTD.5=0;
             PORTD.6=0;
             lcd_gotoxy(0,1);
             lcd_putsf("CAL PC 200 ");
             break;
         case 9:
             PORTD.0=1;
             PORTD.1=0;
             PORTD.4=0;  
             PORTD.5=0;
             PORTD.6=0;
             //lcd_gotoxy(0,1);
             lcd_putsf("CAL PC 500 ");
             break;
         case 10:
             PORTD.0=0;
             PORTD.1=0;
             PORTD.4=0;  
             PORTD.5=0;
             PORTD.6=0;
             lcd_gotoxy(0,1);
              lcd_putsf("CAL PC 1000");
             break; 
         default:
             PORTD.0=0;
             PORTD.1=0;
             PORTD.4=1;  
             PORTD.5=1;
             PORTD.6=0;
             //lcd_gotoxy(0,1);
             //sprintf(str_buffer,"ERROR PC - %u",PC_COUNTER) ;
             lcd_putsf("INC MAG");
             PC_COUNTER=1;

       };
}


/*------------------------------------------------------------------------------
 Procedure:    ADC_DELAY
 Inputs:        DELAY (STEP) TIME
 Return:        none
 Description:    DELAY +/- 2.5%
------------------------------------------------------------------------------*/
void ADC_DELAY(unsigned int delay_time)
{
    actual_delay_time=65535 - (delay_time*2-3);
    if ( volt < 128)
    {  
        actual_delay_time= 65535 -(( delay_time -  (delay_time  / 100) * (10 - (8 * volt  / 100  ) ) ) )*2-3; 
    }  
    if (volt > 128 && volt < 256)
    {
        actual_delay_time= 65535 -(( delay_time + (delay_time  / 100) * (8 * (volt - 128) / 100 ) ) )*2-3;
    }
      
    if (volt == 127 || volt == 128)
         actual_delay_time=65535 - (delay_time*2-3);     
        
   WDTCR=0b00001111;                             
}

/*------------------------------------------------------------------------------
 Procedure:    DELAY
 Inputs:        none
 Return:        none
 Description:    Vary the Delay of signal
------------------------------------------------------------------------------*/
void DELAY(void)
{
     lcd_gotoxy(0,0);       
     switch (FREQ_COUNTER)
       {
         case 2: 
             ADC_DELAY(10000);
             lcd_putsf("PUL NO 2 ");
             break;  
         case 4:                      
             ADC_DELAY(5000); 
             lcd_putsf("PUL NO 4 ");
             break;
         case 6:
             ADC_DELAY(3333);
             lcd_putsf("PUL NO 6 ");
             break;
         case 8:
             ADC_DELAY(2500);
             lcd_putsf("PUL NO 8 ");
             break;
         case 10:
             ADC_DELAY(2000);
             lcd_putsf("PUL NO 10");
             break;   
         case 12:
             ADC_DELAY(1667);      
             lcd_putsf("PUL NO 12");
             break;  
         case 14:
             ADC_DELAY(1428);
             lcd_putsf("PUL NO 14");
             break;
         case 16:
             ADC_DELAY(1250);
             lcd_putsf("PUL NO 16");
             break;
         case 18:
             ADC_DELAY(1111);
             lcd_putsf("PUL NO 18");
             break;
         case 20:
             ADC_DELAY(1000);
             lcd_putsf("PUL NO 20");
             break;   
         case 22:
             ADC_DELAY(909);     
             lcd_putsf("PUL NO 22");
             break;  
         case 24:  
             ADC_DELAY(833);
             lcd_putsf("PUL NO 24");
             break;
         case 26:
             ADC_DELAY(769);
             lcd_putsf("PUL NO 26");
             break;
         case 28:
             ADC_DELAY(714);
             lcd_putsf("PUL NO 28");
             break;
         case 30:
             ADC_DELAY(667);
             lcd_putsf("PUL NO 30");
             break;   
         case 32:    
             ADC_DELAY(625);
             lcd_putsf("PUL NO 32");
             break;  
         case 34:
             ADC_DELAY(588);
             lcd_putsf("PUL NO 34");
             break;
         case 36:  
             ADC_DELAY(556);
            lcd_putsf("PUL NO 36");
             break;
         case 38: 
             ADC_DELAY(526);
             lcd_putsf("PUL NO 38");
             break;
         case 40:   
             ADC_DELAY(500);
             lcd_putsf("PUL NO 40");
             break; 
         default:
             ADC_DELAY(500);
             //sprintf(str_buffer,"ERROR-%u",FREQ_COUNTER)  ;
             lcd_putsf("INC/DEC"); 
             FREQ_COUNTER=2;
       };     
      
}