Monday, October 31, 2011

Sleep and Wake PIC Microcontrollers

Discription :
PIC microcontrollers SLEEP feature is an extremely useful mechanism to minimize power consumption in battery-powered applications.In sleep mode,the normal operation  of a pic microcontroller is suspended and clock oscillator is switched off.The power consumption is lowest in this state.The device can be woken up by an external reset,a watch-dog timer reset,an interrupt on INT0 pin,or port-on-change interrupt.In this experiment,we will discuss how to put PIC microcontroller into sleep mode and compare the current consumption during sleep mode and the normal operation mode .

Theory :
In sleep  (power-down) mode,a PIC microcontroller is placed in it's lowest current consumption state.The device goes into sleep mode by executing a SLEEP instruction.The device oscillator is turned off,so no system clocks are occurring in the device.However,the I/O ports maintain the status they had before the SLEEP instruction was executed.Therefore,in order to minimize the power consumption in sleep mode,the output ports must not be sourcing or sinking the current before going into sleep mode.Besides,all the unused I/O pins should be configured as inputs and pulled either high (Vdd)  or low (Vss).
Several events can make the device wake-up from the sleep mode :

  1. Any device reset.
  2. Watchdog timer wake-up (if WDT was enabled).
  3. Any peripheral module which can set its interrupt flag while in sleep, such as :
  • External INT pin
  • Change on port pin
  • Comparators
  • A/D conversion
  • Timer1
  • LCD
  • SSP
  • Capture;etc.
The first event (device reset) will reset the device upon wake-up. However the latter two events will wake the device and then resume program execution.When the SLEEP instruction is being executed,the next instruction (PC+1) is pre-fetched,so that on wake-up the processor could execute the next instruction after the SLEEP command.For the device to wake-up through an interrupt event,the corresponding interrupt enable bit must be set (enabled).Wake-up is regardless of the state of the GIE bit.If the GIE bit is clear (disabled),the device will just wake up from sleep and continues executing the program from the instruction right after the SLEEP command.If  the GIE  bit is (enabled),the processor will execute the instruction after the SLEEP instruction and then branches to the interrupt address (0004h).Therefore,if an interrupt is to be used just to wake up the PIC microcontroller,the GIE bit must be cleared before the sleep instruction.


Watchdog timer (WDT) :
The watchdog timer or WDT is an independent timer with its own clock source.It provides a way for the PIC processor to recover from a software error that obstruct from program continuation,such as an endless loop.It is a free-running timer which,if allowed to overflow, will automatically reset the PIC .The WDT is enabled/disabled by a device configuration bit,WDTE.If it is enabled,software execution may notdisable this function.To prevent a time-out condition the watchdog must be rest periodically via software.In 16f628A the watchdog timer has a nominal time-out period of 18ms,which can be extended up to 2.3s by using a prescaler with a division ratio of up to 1:128.The prescaler rate is selected through PS0-PS2 bits of the OPTION register.Note that the PSA bit must also be set to assign the prescaler to WDT,otherwise it will be used by timer0.

In normal operation,if the watchdog timer is enabled,a WDT reset instruction (CLRWDT° is placed in the main loop of the program,where it would normally be exepected to be executed often enough to prevent the WDT overflow.If the program hangs,and the CLRWDT instruction is not executed in time,the program counter is reset to 000 so that the program restarts.
However ,if the PIC microcontroller is in sleep mode, a WDT time-out will not reset the device ,but just causes it to wake up (know as WDT wake-up) and the microcontroller continues program execution from the instruction following the sleep instruction.
Note : When a sleep instruction is executed,the watchdog timer is cleard.But the WDT will keep running if it has been enabled .
Sleep mode is extremely useful in battery-powered data-loggers where the measurement samples are to be taken with some sampling interval.Between successive data samples,the microcontroller can be put into Sleep mode to prolong the battery life .
Experimental setup :
The setup for this experiment would be as shown in the circuit diagram below.The pic 16f628A runs at 4.MHz clock using an external crystal.An LED is connected to RB0 port pin,which glows for 5sec after every 4.3 second delay .During the first half of the delay (2.3 sec),the microcontroller  is put to slepp mode and WDT time-out wakes it up.The remaining 2 sec delay is created through a software routine using NOP instruction. An ammeter is connected in series between the power supply voltage and the microcontroller circuit to monitor the current consumption of the circuit.The MCLR pin is pulled high through a 10k resistor.
Software :
The following program is written in c and compiled with mikroC for pic. The OPTION register is configured to assign prescaler to WDT .The prescaler ratio of 1:128 creates the WDT time-out duration of approximately 2.3sec.An additional software delay of 2 sec is created using the delay_ms() library routine.The amount of current consumption during both the delay intervals is displayed on the digital meter.

/* Project name:
     Understanding sleep mode in PIC microcontrollers
 * Copyright:
     charaf zouhair
 * Test configuration:
     MCU:             PIC16F628A
     Oscillator:      XT, 4.0000 MHz
*/

sbit LED at RB0_bit;       // LED is connected to PORTB.0

void main() {
TRISB = 0b00000000;
TRISA = 0b00100000;
LED = 0;
OPTION_REG = 0b00001111;   // Assign 1:128 prescaler to WDT
do {
  asm sleep;               // Sleep mode, WDT is cleared,
                           // and time out occurs at Approx. 2.3 Sec
                           // Current is minimum in Sleep mode
  LED = 1;                 // After wake-up the LED is turned on
  Delay_ms(500);
  LED = 0;
  asm CLRWDT;              // Clear WDT
  Delay_ms(2000);          // Measure current here and compare with Sleep mode
 }while(1);                // current
}

The watchdog timer should be enabled in the configuration registers.In mikroC ,this can be done through the edit project window 
Output :
The current consumption during software delay routine (led is off) was found as high as 940 µA,whereas the sleep mode current was only 43 µA.This is a significant reduction in pic power consumption.


Summary :
PIC microcontrollers Sleep mode is a low current mode where the power consumption is minimum It is extermely useful in battery-powered applications to prolong the battery life.If you are making a battery-powered data logger,it would be a smart move to put the microcontroller into sleep mode during the time when it is not sampling the data value,and it can be waken-up by WDT time-out.In 16f628A ,the use od sleep mode WDT wake-up provides a maximum sleep duration of 2.3 sec .But if your data logger design requires a longer sampling interval between two successive data samples and you want to put the microcontroller into sleep mode during most of this interval,you can use multiple SLEEP instructions in sequence. When the microcontroller wakes up from the first sleep by WDT time-out; it resumes normal operation and executes the next instruction. If it finds another SLEEP instruction, it will reset the WDT and go back to sleep mode again,thus prolonging the sleep duration.The test circuit used in this experiment illustrated that the pic current consumption is significantly lower (more than 20 times less )in sleep mode than in normal execution mode .

for more information contacte me : charaf_zohair@hotmail.com

Thursday, October 27, 2011

Understanding Interrupts

Description :
Interrupts are powerful concept embedded systems for controlling events in time-critical environment .In a typical embedded system,the embedded processor (microcontroller) is responsible for doing more than one task (but can do only one at a time ).For example let's say a programmable digital room thermostat,the microcontroller is assigned to monitor the room temperature,turn the AC or heater ON znd OFF,control the LCD display,and respond to any new temperature setting from the user.Out of these the first three taskes are non-time-critical and are executed continuously in sequence one after the other,within the main loop.But when the user presses any button on the setting panel,the microcontroller should be able to read it before the user releases the button.So this is a time-critical event and microcontroller should stop whatever it is doing and responding to this higher priority event.This is possible through the use of interrupts.This tutorial first describes the interrupt system in general and then illustrates how it is handled in PIC Microcontrollers.
Theory :
As mentioned above,interrupts form the basis for separating the time-critical events from the others and execute them in a prioritized manner.An interrupt tells the microcontroller to drop whatever it is doing and execute another program (the Interrupt Service Routine or ISR)stored at a predefined place in the program memory. interrupt requests are asynchronous events which means that an interrupt request can occur at any at any time during the execution of a program.But whenever it occurs,the CPU finishes the current instruction and stores the address for the next instruction (which is in the program counter,or pc) in to the stack memory so that the current program can continue once the interrupt service ends.The CPU them jumps to a certain program memory location (0x0004 in the PIC),where the ISR  begins.At the end of the ISR,execution of the return instruction loads the address at the top of the stack back into the program counter,and execution proceeds from the same point where the processor was interrupted.
A microcontroller has several sources of interrupts,which can be external or internal.The most common internal interrupt sources are timers,EEPROM,ADCmodule,and comparator,External interrupts originate in peripherals and reach the microcontroller through one of its pins and associated ports.
Interrupts in medium-end PIC microcontrollers are fixed,maskable interrupts.This means that interrupts can be globally enabled or disabled,as well as each interrupt source can be individually enabled or disabled. We will consider the PIC 16f688 microcontroller for today's discussion on interrupts.
The PIC 16f688 has the following sources of interrupt :
  • External interrupt at RA2/INT pin
  • TMR0 Overflow Interrrupt
  • portA change Interrupts
  • 2 Comparator Interrupts
  • A/D Interrupt
  • Timer1 Overflow Interrupt
  • EEPROM Data Write Interrupt
  • FAIL-Safe Clock Monitor Interrupt
  • EUSART Receive and Transmit interrupts
Each of these interrupts can be enabled or disabled individually,and more than one interrupt can be active at the same time.When an interrupt is requested,the microcontroller finishes executing the current instruction,stores the value of the program counter in the stack,and jumps to address 0004h in program memory,where the ISR is located.As all interrupt sources make the program to jump to the same place(0004h),the programmer,when writing the ISR,must first find the sepcial function registers,INTCON and PIR1,associated with the interrupt system.The figure below shows the bits in the interrupt control register (INTCON).
Te details for each bit are describehd here :
GIE (global interrupt enable) : This bit is the master switch for all interrupts.Turn it off (GIE=0) and no interrupts are enabled (regardless of the state of their individual enable bits).Turn it on (GIE=1) and interrupts whose individual enable bits are set will be enabled.When an interrupt is requested,this bit is automatically set to 0,thus any further interrupts. The return instruction at the end of the interrupt service subroutine sets bit GIE back to 1,thus enabling the global interrupt system.
PEIE(peripheral interrupt enable) : Is a mini-master switch for a group of interrupts which are know as 'peripheral interrupts'.They have thier own enable bits in the PIE1 register (discussed later).This bit must be set to enable any enabled peripheral interrupts.
T0IE,T0IF : These bits are related to timer0 overflow interrupt.When T0IE=1,the timer0 interrupt is enabled.T0IF is set to 1 whenever TMR0 overflows from 255 to 0.This discussed in PIC Timers and Counters article too.
INTE,INTF : These bits are related to the external interrupt which depends on the state of the RA2/INT  pin of PIC 16f688 .Bit INTE  enables this interrupt. The interrupt can be set to trigger on the rising edge or falling edge of the signal on INT pin.This is done using the bit 6 (INTEDG) of the OPTION register (shown below).Bit INTF is a flag that indicates the detection of an edge (rising or falling) in the pin INT .
RAIE,RAIF : These bits are related to the interrupt due to change of logic level at PORTA pins.RAIE=1 enables this interrupt and RBIF is a flag that indicates a change in one of the pins of PORTA.In order to select which PORTA pin should be able to trigger the interrupt,the corresponding bit of INTERRUPT-ON-CHANGE PORTA (IOCA)register must be set.
The individual bits of OPTION,PIE1 and IOCA registers are shown in the figures below .

Please read datasheet of 16f688 for the detail description of these registers.In the folowing section,we will discuss how to program the interrupt that originates in the RA2/INT line of 16f688.
In order to intialize the RA2/INT interrupt,the following operations must take place :

  1. PortA ,line2(RA2) must be intialized for input
  2. The interrupt source must be set to take place either on the falling or the rising edge of the signal using INTEDG bit of OPTION-REG.
  3. The external interrupt flag (INTF in the INTCON Register) must be initially cleared
  4. Global interrupts must be enabled by setting the GIE bit in the INTCON Register
  5. The External Interrupt on  RA2/INT must be enabled by setting the INTE bit in the INTCON Regester.
A sample program using RA2/INT interrupt is developed later in this articale

Circuit Diagram :
In the circuit diagram shown below,a push button switch is wired to the RA2 port of 16f688.This switch produces the interrupt when pressed.Four red color LEDs are connected to RC0 trough RC3 port and an yellow led is wired to port RA0.The main program is a 4-bit binary up counter that increments at rate of approximatley one second.The value of the counter is sent to PORT-C and displayed on the four red LEDs.The yellow LED is toggled on and off when the pushbutton switch is pressed .The switch is active low and therefore,the interrupt is programmed on the falling edge of the signal(INTEDG=0).The 16f688 runs at 4MHz clock derived from the internal source.
Software :
The Interrupt Service Routine (ISR) depends on the specific application.However,certain steps are applicable to all cases.For example,the ISR should begin by checking which particular event triggered the interrupt(if more than one input is enabled).In this case,the INTF bit of INTCON regidter must be checked to verify that the cource of interrupt is from RA2/int pin.Similary,the interrupt flag(INTF bit in INTCON register)lust be cleared by the ISR before returning to the main program otherwise an endless series of interrupts will occur.This is because on return the CPU finds the interrupt flag still set and assumes it as another interrupt and jumps back to ISR.
In PIC microcontrollers,the processor automaticlly clears the GIE bit in the INTCON register when an interrrupt occurs.This means that no interrupt can take place in the ISR,otherwise you can imagine the havoc that would take place if it should not be the case.When the processor executes the return statement in the ISR,the GIE bit is set and the interrupts are enabled again.
The interrupt programming for this experiment is written in mikroc pro for pic.it is a C compiler for PIC from mikroElectronika .In mikroc,the ISR is written just like another subroutine but with a reseved name,interrupt.Within the ISR,appropriate flag bits are checked to identify the source of interrupt.The complete program for this experiment is given below.

/*
Lab 16: Understanding Interrupts
MCU: PIC16F688
Internal Clock @ 4MHz, MCLR Enabled, PWRT Enabled, WDT OFF
by charaf zouhair
oct 27, 2011
*/

sbit LED at RA0_bit;  // Interrupt LED
unsigned short count;

// Interrupt service routine
void interrupt(){
 if(INTCON.INTF == 1) LED = ~LED;
 delay_ms(200);   // Key debounce time
 INTCON.INTF = 0;
}

void main() {
 ANSEL = 0b00000000;    // All I/O pins are configured as digital
 CMCON0 = 0x07 ;        // Disbale comparators
 TRISC = 0b00010000;    // PORTC all outputs except RC4
 TRISA = 0b00000100;    // PORTA all outputs except RA2
 INTCON = 0b10010000;   // Set GIE and INTE bits
 OPTION_REG.INTEDG = 0; // External interrupt on falling edge of RA2/INT pin
 count = 0;
 LED = 0;
 PORTC = count;
 do {
  count ++;
  if (count ==16) count =0;
  PORTC = count;
  delay_ms(1000);
 }while (1); // infinite loop
}
Output:
You will see the microcontroller will keep counting from 0 to 15 and roll over to 0 again and keep it continue.Whenever you press the interrupt switch,the processor will respond to it by changing the status of the yellow LED and then will resume the counting  task

Summary :
  • An interrupt is an event that requires the CPU to stop normal program execution and perform some service (the ISR) related to the event.
  • An interrupt can be generated internally (inside the chip by ADC,EEPROM,TIMERS,etc) or externally (outside the chip through the INT pin).
  • proper use of interrupts allows more efficient utilization of the CPU time.
  • Interrupts are very helpful to perform time-critical applications.Many emergent events,such as power failure and process control,require the CPU to take action immediately.
The interrupt mechanism provides a way to force the CPU to divert from normal program execution and take immediate actions.
References:
PIC MICROCONTROLLER


for more information contact me : charaf_zohair@hotmail.com


Tuesday, October 25, 2011

Elictric cars

Introduction :
What would the cars run on if one day the fuels that we have been lavishing on for so long just disappeared ?
Earth had once been a planet replete with stockpiles of consumable fossil fuels like coal and petroelum.But as mankind progressed and advanced its appetite for energy shot up to humungous proportions and in much less than three centuries since the industrial revolution, there is an outcry to conserve these natural resources and look for alternatives.
The fragile ecology of the earth is gravely in danger due to the side effects of sush rampant use of these depleting resources.Of all the industries that would directly or indirectly hit the consumers if these fuels disappeared from earth,the most obvious would be the automobile industry.To offer a viable solution to these dilemmas,many innovations in the field of automobile industry have taken place from time of time.One of them is ELECTRIC CARS a solution from a cleaner and healthier tomorrow.
History :
An electric car is an automobile run by electric motors which derive their energy from battries.It is a sub-set of Electric Vehicles and generally refers to vehicles running on the road only (others might be trains and boats).These were popular in late 19th century and early 20th century before people lostinterest in them owing to rapid advances in the internal combustion engine technology.The origines of electric care date back to the seconde quarter of the 19th century when ROBERT ANDERSON invented the first crude electric carriage.Thomas Davenport is credited with building the first electric vehicle in the from of a small locomotive.By the turn of the century,cars with three variants,steam,electric nad gasoline were available out of which electric cars had the highest market share.It was a time when cars were used only for short distance travel.but then,due to increased interest in IC engine based automobiles, electrics cars almost disappeared by 1935
The 1960s and 70s witnessed a short revival of interset in electric car technology due to the need for alternative-fuel vehicles to reduce exhaust emissions of IC engines.Companies like Battronic truck company.General electric,Sebring-Vanguard and Elcar Corp;American motor Company etc cashed on this need to roll out electric cars and vehicles. Last decade of the millennium saw renewed interest in electric cars when many nations took several legislative and regulatory actions like emission level regulations,Clean Air Act Amendment (US) etc.which worked in favor of electric car technology Some vehicles from this era are the Chevrolet S-10 Geo Metro,Ford Ranger Pickup,General motors EV1 etc.It is working something like fashion industry,old fashion being brought back in new clothes and fad .
Structure of Electric Cars :
Electric vehicles are one of the simplest forms of self propelled mechanical transport.In the basic design, the drive trainof the car is made up of battery array connected to an electric motor via a swithc.The amount of electricity that is allowed to pass through to the electric motor and gear systems is controlled such that the electric motor drives the weels in the most efficient manner.Thus,they key elements that differentiate an electric car from other cars and also from the heart and core of this type are :

    1. Electric motor :The car may run on AC or DC motors.If it uses a DC motor,the may run on any voltage between 96V and 192V of the rating 20KW.Motors work on the principle of electromagnetic induction where change in magnetic flux causes the central shaft to rotor.DC motors can be overdriven at a value much greater than the normal operating point thus offering short burst of increased horsepower.Overdriving for long spells lead to overheating of the motor to a point where it may be destroyed .In case of AC motors,3phase motors are generally used which run at 220-240 Volts along with 300 Volt battery packs.AC motors have the ease of availability in varous sizes,shapes and power ratings in contrast to DC motors and also have a 'regenerative braking' feature by virtue of which, the motor can as a generator to change the batteries while braking .
    2. Motor Controller : This is the part of the system which would control the amount of current being supplied to the motor depending on amount of pressure on the accelerator pedal.The accelerator is connected to potentiometers which act as variable resistors to provide the signal on how much power to deliver.When the pressure on accelerator is Zero,no power is deliverd and full power is delivered when a pedal has been fully pressed.In case of DC motors the controller would chop the values of DC supply voltage to obtain a current with average value that is proportional to the amount of pressure applied to the accelerator.This chopping or pulsing takes place at a rate of more than 15000 cycles per second to avoid the humming sound in the human hearing range.In case of three phase AC motors,the controllers need to create 3 pseudo sine waves by taking DV voltage from batteries and then pulsating them on and off while inverting the polarities 60 times a second.This requires 6 sets of transistors,three for the pulsing and the other 3 for inversion of the signals. This is a little more complex than a simple DC motor controller.
    3. Batteries : Batteries are the parts that hold the energy reserve for the entire car operation.These store energy in the form of chemical energy and them back to electrical when required despite of all the advances in technology,battery still remains the weakest link in the chain.Lead acid batteries find predominant use in today's cars.These are heavy,bulky,take a lot of time to charge and yet have limited capacity and life.Better replacments in the form of LiMH batteries do exist,which not only double the range of cars but also have siginificatly longer lives,are present but at present are too expensive to invest in.Fuel cells offer the most attractive solution to all these problems along with being environment friendly,but still need a lot of R&D before they enter the mainstream market.  

Electric cars V/S Gasoline Cars
In the making of an electric car,a few get replaced from a conventional gasoline driven car .Firstly,The internal combustion engine,which is replaced by an electric motor. It gets power from a controller which is further connected to an array of rechargeable batteries.On a higher level of abstraction,a gasoline car might look like a plumbing project with fuel lines,exhaust pipes,hoses etc.While an electric car may look more a wiring project.The difference in sound levels might be oblivious to a person standing outside,but the one sitting inside would notice that the electric car is almost silent,even while running.The electric parts are supplemented by little changes of tha car like the fuel guage being replaced by voltmeter, the engine vacuum used in power brakes being replaced by a vacuum pump,the manual transmission being replaced by a switch etc.Though these designs may very from vendor to vendor and car to car,the first three parts discussed are essential to any electric car.Apart from these,there are a few subtle differences which can be draw as in the figure below
Comparing the two solely on initial pricing would always give gasoline cars an upper hand.On closely seeing the performance of electric cars,it is observed that they offer an advantage of up to 30% on each kilometer driven. And each battery pack which usually lasts around 2 to 3 years is capable of running 25,000 km.
Benefits :
These also have many potential benefits.First andforemost os the reduction in the emission lelvels of the car.Pollution has been a bane,adversely affecting ecology as well as making it uncomfortable for everyone who has to live with it.Through almost zero tailpipe emissions,green house gas relese into the atmosphere is reduced.Along with it,the dependence of any country going for electric cars reduces it dependency on foreign nations for its fuel supply which directly affects the state of economy.Moreover,electric motors have relatively high conversion efficiencies of up to 75% as compared to IC engines which convert only 20% of gasoline energy at maximum.
Despite of the promise of greener pastures by the electric car,it is yet to entre the automobile mainstream.It faces several hurdless and limitations in being adopted by all and sundry.First facotr that backs people off such an alternative is the initial cost of car.The main component of this cost is the battery pack.With mass production, it is expected that the rates will decline.But investments on expectations are highly risky and not many people want to take such a leap of faith.other facotrs are the lack of public infrastructure to overcome the 'range anxiety',where a driver  gears that the battery might just run out before reaching home and there is no charging point around.Most of the electric vehicles are not capable of high speeds.
As of 2011,there are only a few highway-capable models available in the market.Electric cars aare aimed at reducing the use of fossil fuels.But this makes us think that where does the energy to produce electricity com from?Many power plants still rely on fossil fuels to operate their boilers.Thus complete migration would only be possible only when there is a huge investment to replace the existing infrastructure and its dependence on fossil fuels.Most people would be plugging in thier cars to recharge at night when it is not use.This could also cause potential load problems on the electric grid .Also,the batteries would charge using the conventional 220V sockets and hence would take all the more time to recharge.A possible solution to this would be to have a smart energy plan where the charging would be done on 'level 2' 240 Volts charger rather than the conventional 120V chargers, reducing charging time and for this,a large load would be given to the gird.Fuel cells offer much promise on many fronts like weight reduction,increased battery performance and life,capacity etc.And are an area of active reseach .Hydrogen as a fuel would reduce the harmful emissions to Zero and is quite abundant.
Current Scenario :
Several countries like US,UK,and china have pledged federal grants for electric cars anf batteries to hasten up the process.Local governments offer tax credits,subsidies and incentives to reduce the purchase price of electric cars.Many European Union member states provide tax reductions and exemptions for people going in for purchasing electric cars.Many companies like America Electric,commuter cars,EIBiI Norge,Fly Bo,Global Electric Motocars (GEM),Modec,REVA ect.Have been rolling out various electric car models. The influence has been such that even IC engine car manufacturers have started to manufacture electric car variants.Some of the common names are Toyota,hyundai,Mahindra,Honda,Chevrolet,Nissan etc
Despite of all the marketing startegies and all the push being given by the governments to popularize electric cars among the people,not everybody understands the importance of switching  over to alternative energy solutions right now .And the scenario is expected to remain so until the manufacturing cost is brought down and the performance is brought up to the level where they can directly compete with the gasoline cars and outdo them.This all round up again to the weakest link in the electric car manufacture chain,the batteries .But we will need to understand the need ,if not for us then for the generations to come.Electric car is one such investment !
thanks

Sunday, October 23, 2011

pic 16f877 and LCD 16X2 character

discription :
HD 44780 based displays are very popular among hobbyists because they are cheap and they can display characters.Besides they are very easy to interface with microcontrollers and  most of the present day high_level compilers have in_built library routines for them.Today ,we will see how to inteerface an HD44780 based character LCD to a pic 16f877 microcontroller.The interface requires 6 input/output lines of the pic 16f877 : 4 data lines and 2 control lines.A blinking test message ,"hi Im charaf zouhair welcome to my blog ", will display on the LCD screen

Required Theory :
All HD 44780 based character LCD display are connected through 14 pins : 8 pins data pins (D0-D7), 3 control pins (RS,E,R/W), and three power lines (Vdd,Vss,Vee).some LCDs have LED backlight feature that helps to read the data on the display during low illumination conditions. so they have two additional connections (LED +and LED-), making altogether 16 pin. A -pin LCD module with its pin diagram is shown below
Control Pins :
The control pin RS determines if the data transfer between the LCD module and an external microcontroller are actual character data or command/status.when the microcontroller needs to send commands to LCD or to read the LCD status,it must be pulled low.Similarly,this must be pulled high if character data is to be sent to and from the LCD module.

The direction of data transfer is controlled by the R/W pin. if it is pulled low, the commands or character data is written to the LCD module. and when it is pulled high, the character data or status information from the LCD registers is read. here,we will use one way data transfer,from microcontrollerto LCD module, so the R/W will be grounded permanently.

The enable pin(E) initiates the actual data transfer.when wrting to the LCD display, the data is transferred only on the high to low transition of the E pin .

Power Supply Pins :
Altough most of the LCD module data sheets recommend +5V DC. Supply for operation,some LCDs may work well for a wider range(3 to5.5V).The Vdd pin should be connected to the positive power supply and Vss to ground.Pin 3 is Vee,which is used to adjust the contrast of the display.In the most of this cases, this pins is connected to a voltage between 0 and 2V by using a present potentiometer.

Data Pins :
Pins 7 to 14 are data lines (D0-d7) data transfer to and from the display can be achieved either in 8-bit or 4-bit mode . The 8-bit mode uses all eight data lines to transfer a byte,whereas ,in a 4-bit mode,a byte is transferd as two 4-bit nibbles .In the later case,only the upper 4 data lines (D4-D7) are used.This technique is beneficial as this saves 4 input/output pins of microcontroller.We will use the 4-bit mode.
For further details on LCDs please visite this site mybe helpfull http://lcd-linux.sourceforge.net/pdfdocs/lcd1.pdf
http://lcd-linux.sourceforge.net/pdfdocs/lcd2.pdf

Circuit Diagram:
Data transfer between the MCU and the LCD module will occur in the 4-bit. the R/W pin (5) of the LCD module is permanently grounded as there won't be any data read from the LCD module .RC0-RC3 serves the 4-bit data lines (d4-d7,pins 11-14) of the LCD module. control lines,RS and E ,are connected to RC4 and RC5 . Thus ,altogether 6 I/O pins of the 16f877 are used by the LCD module.The contrast adjustment is done with a 5K potentiometer as shown below  If your LCD module has backlight LED, use a 68 ohom resistance in series with pin 15 or 16 to limit the current through the LE .the detail of the circuit diagram is shown below.



Software :
The LCD data and control lines are driven through PORTB,so it must be defined as output port (TRISB=0).You need   select all I/O pins as digital (adcon1=0x07).The programming of an HD 44780 LCD is a little bit complex procedure as it requires accurate timing and proper sequence of various control signals and commands.But luckily, the MIKROC pro for pic has library routines to communicate with a standard HD44780 based LCD module using 4-bit mode.This makes programming a lot easier before using the built-in functions for LCD, the connections of LCD pins to the PIC microcontrollers must be defined. The comments are provided in the source code to understand how to use the library routines for LCDs in MIKROC pro for pic
/*
Lab 3: blink character message on LCD using 16f877
Internal Oscillator @ 8MHz, MCLR Enabled, PWRT Enabled, WDT OFF
Oct 23,      2011 by charaf zouhair
*/

sbit lcd_rs at rb0_bit;
sbit lcd_en at rb1_bit;
sbit lcd_d4 at rb2_bit;
sbit lcd_d5 at rb3_bit;
sbit lcd_d6 at rb4_bit;
sbit lcd_d7 at rb5_bit;
//***************************************************************************
sbit lcd_rs_direction at trisb0_bit;
sbit lcd_en_direction at trisb1_bit;
sbit lcd_d4_direction at trisb2_bit;
sbit lcd_d5_direction at trisb3_bit;
sbit lcd_d6_direction at trisb4_bit;
sbit lcd_d7_direction at trisb5_bit;
//**********************************************************************
char text1[]="CHARAF ZOUHAIR";
char text2[]="THIS IS MY BLOG";
char text3[]="MOROCCO";
char text4[]="ELECTRONICS";
//******************************************************************
void main() {
  adcon1=0x07;
trisb=0;
portb=0;
lcd_init();
lcd_cmd(_lcd_clear);
lcd_cmd(_lcd_cursor_off);
lcd_out(1,1,text1);
lcd_out(2,1,text2);
delay_ms(5000);
lcd_cmd(_lcd_clear);
lcd_out(1,6,text3);
lcd_out(2,4,text4);

}

i want to share with you this book : http://goo.gl/5Eqhi

For more information about code contact me : charaf_zohair@hotmail.com

how to take input with pic 16f877

Discription :
Any microcontroller based system typically has an input and a corresponding output .taking simple output  with a pic micocontroller has been explained  in led blinking with pic 16f877 .this article i will explain you how to provide an input to the pic and get corresponding output using pic 16f877
PIC 16f877 series normally has five input/output ports.they are used for the input/output interfacing with other devices/circuits.Most of thses port pins are multiplexed for handling alternate function for peripheral features on the devices.All ports in PIC chip are are biderctional .When the peripheral action is enabled in a pin, it may not be used as its general input/output functions.The PIC 16f877 chip basically has 5 input/output ports. the five I/O PORTS its functions are given below .
  1. PORTA and the TRIS A Registers
  2. PORTB and the TRIS B registers
  3. PORTC and the TRIS C registers
  4. PORTD and the TRIS D registers
  5. PORTE and the TRIS E registers
To configure a particular ports/pin as input ,the corresponding TRIS register/TRIS bit should be set to high(1=5v).for output,and TRIS register/bit should be set to low (0=0v)
for example :
for port D ,to set the entier port D as input
TRISD=11111111=0XFF
for set the port d as out put
TRISD=0b0000000=0
In this program, a switch has been conncted on port pin RA0 of port A to provide input to the microcontroller .The input is monitored as an output on LED connected to pin RD0 .The connections are show in the figure 1

CODE :
Lab 2: switch on LED by button with PIC16F877
Internal Oscillator @ 4MHz, MCLR Enabled, PWRT Enabled, WDT OFF
Oct 23,      2011 by charaf zouhair
*/
void main() {
adcon1=0x07;
TRISD = 0b00000000; // PORTC All Outputs
TRISA=0B11111111;

while(1) {
if (porta.f0==0){portd.f0=1;}
else
portd.f0=0;
}
for more information about code contact me charaf_zohair@hotmail.com

Friday, October 21, 2011

flashing led by microcontroller

Discription :
today is not first session in PIC microcontroller project.but i want to show you first lab for everyone want be programming .We will begain with an experiment that flashes an LED on and off.while this looks very simple it is best project to start because this makes sure that we successfully wrote the program,compiled it ,loaded inside the PIC ,and the circuit is correctly built on the breadboard .
in this lab session we will connect an LED to one of the port pin of pic 16f877 and flash it continuously with 1 sec duration
Required Theory :
you must be know that :

  • Digital I/Oports of pic 16f877
  • direction control registers;(TRISA , TRISB,TRISC.TRISD.TRISE)
  • special fonction registers ADCON1 
Circuit Diagram :
for this lab we sill add a light-emitting-diode (led) to port pin RC2(17) with a current limiting resistor (330 ohm)in series .
Software :
Open a new project window in mikroC and select Device Name as pic16f877.nect assing 4MHz to device clock.go to next and provide the project name and the path of folder.it isalways a good practice to have a separate floder for each project. Creat a folder named lab1 and save the project inside it with a name (say, first project).The mikroC project file has.mccpi extension.the next window is for "add file to project". leave it blank ( there are no files to add to this project ) and click next. The next step is include libraries , select include all option . next ,click finish button. You will see a program window with void main()function already included. now goto project >Edit project you will see the following windows
this window allows you to program the configuration bits for the 14-bit CONFIG register inside the pic 16f877.the device configuration bit allow each iser to customize certain aspects of he device(like reset and oscillatore configurations)to the needs of the application .when the device powers up,the state of thses bits determines the modes that  the device uses.
therefore,we also need to program the configuration bits as per experimental setup.select,
oscillator
watchdog
power up timer
master clear enable
code protect
data EEread protect
brown out detect
internal external switch over mode
monitor clock fail-safe
not that we have turned on power-up timer, it provides an additional delay of 72ms to the start of the program execution so that the external power supply will get enough time to be stable.It avoids the need to reset the MCU manually at start up.
  • Here is the complete program that must be compiled and loaded into pic16f877 for flashing the LED. Copy and past this code to program in your main program window. you have to delete the voide main() function first that was already included . to compile, hit the builed button, and if there were no errors,the output HEX file will be generated in the same floder where the project file is then load the HEX  file into the pic16f877 microcontroller using your programmer 

for more information about hex file just contact me charaf_zohair@hotmail.com

Lab 1: Flashing LED with PIC16F877
Internal Oscillator @ 4MHz, MCLR Enabled, PWRT Enabled, WDT OFF
Copyright @ Rajendra Bhatt
Oct 21,      2011 by charaf zouhair
*/
// Define LED @ RC0
sbit LED at RC0_bit;
void main() {
adcon1=0x07;
TRISC = 0b00000000; // PORTC All Outputs

do {
LED = 1;
Delay_ms(1000);
LED = 0;
Delay_ms(1000);
} while(1);  // Infinite Loop
}

12V Batteries charger circuit

This batteries charger circuit can be used to charge one or more batteries with the total nominal voltage of 12V
meaning ten NiCD  battery or 6 2V lead acid.The circuit is pretty small and can be built in a housing network adapter.The incorect usage is impossible :connecting the batteries with reverse polarity ,shortcircuit of the output terminals or power loss have no impact on the charger or battery .
We can use a transformer with 18V on the secondary and then using a doide bridge to rectify the 18V AC voltage we get 22V DC ON C1
The completley discharged batteries are charged at the begining with 6 mA current thru R2-D2 and R6-D1 .One the bat have reached 03-05V, the base-emitter voltage of T1 is high enough to bring the transistor in conduction.
Green LED D4 is used as an charging indicator and opens T1
There is an 60mA current flowing thru R5-R6 , this means that the charging of a 500 mA NiCD battery  will take 12 hours
If the battery is connected with reversed polarity or ther is a shourtcircuit, the power transistor T1 remains blocked and charching current can exceed 6-12mA.the current draw at maximum load around 80mA

Circuit Diagram :




Wednesday, October 19, 2011

Battery Back-up Circuit

This Battery Back-up circuit can be added to surveillance systems or control like alarms to power the circuit during Mains power failure.the battery back-up will immediatly take up the load without any delay
figure 1 show you circuit diagram
the circuit is simple to construct .Regulator IC 7809 volts regulated DC for powering the circuit as well as to charge the rechargeable battery. LED indicates the power on status , when the mains power is available, diode D1 forward biases and passes current into the battery through R2. Value of  R2 is selected to give 90mA current (9/100=0.09A)for slow charching . when the mains power failure D1 reverse baises and D2 forward biases and buck-up the circuit . the same circuit can be used in circuits having 6 volt 7.5 Ah battery.for 12 volt battery , use 7814 regulator IC and 14 volt input

Tuesday, October 18, 2011

Control temperature using LM 35 & 16F877

Description:
i want to make this project for our factory
the objective of this project is to control the temperature of room servers  ; through to set the value of temperature wanted. and let the microcontroller take a decision to switch on or off the fan

How This Project Work :
the temperature is testing by LM35 sensor is given the voltage proportional with the temperature tested; then the microcontroller 16f877 will make compare between the temperature tested and the temperature wanted which will set manually by push-button, after that the pic 16f877 will take decision to start fan and display the  result on lcd at every time the value change it
i will using mikroc program to programming pic 16f877

The Components Need :
pic 16f877
temperature sonsor LM35
lcd 16x2
transistor
relays
resistor
dc power adaptor

Parts Discription
lm 35 sensor


LM 35 is a precision tempreature sensor . This is a small 3 pin IC in TO-92 package remember this is an IC .Its centre pin is output and outher tow are power .The LM35 measures temperature in centigrade .Output  of LM35 IS analog ,uniformly linear over the entire range .It rises by 10.0mV/centigrade .This IC does not require external calibration or trimming .various variants of this commnly used sensore ICare available,which differ in the range of measured temperature.

LCD 16X2 Character
LCDs are becoming more and more popular in electronic devices to communicate with user,there several LCD controllers , each having its own unique communication protocol. hitachI HD 44780 is very popular and industry standard LCD communication controller,this controller is built right on to the LCD modul .Many highlevel programming language provide ready to use libraries for communication with this device .
Transistor :
Most ICs cantnot supply large output currents so it may be necessary to use a transistor to switch the larger current required for output devices such as lmaps ,motors , relays
Atransistor can also be used to enable an IC connected to law voltage supply (5v ) to  switch  the current for an output device with a separte a higher voltage supply (12) . the two power supplies must be linked , normally this is done by linking thier 0V connections
Relays :
Using relays when we face more current flow and cannot transistor to support this current (10Aor more)that's why i prefer to use relays in my projects i know the time of responding is slow than transistor it's around (ms) but transistor around (us) .
The Microcontroller :
Although microcontrollers were being developed since early 1970's real boom came in mind 1990's, A company named Microship  made it's first simple microcontroller ,which they called PIC .Originally this was developed as a supporting device for PDP computers to control it's peripheral devices ,and therefore named as PIC, Peripheral interface Controller.thus all the chips developed by Microship have been named as a class by themselves and called PIC.
Microcontroller Core Features :

• High performance RISC CPU 
• Only 35 single word instructions to learn
• All single cycle instructions except for program
branches which are two cycle
• Operating speed: DC - 20 MHz clock input
DC - 200 ns instruction cycle
• Up to 8K x 14 words of FLASH Program Memory,
Up to 368 x 8 bytes of Data Memory (RAM)
Up to 256 x 8 bytes of EEPROM Data Memory
• Pinout compatible to the PIC16C73B/74B/76/77
• Interrupt capability (up to 14 sources)
• Eight level deep hardware stack
• Direct, indirect and relative addressing modes
• Power-on Reset (POR)
• Power-up Timer (PWRT) and
Oscillator Start-up Timer (OST)
• Watchdog Timer (WDT) with its own on-chip RC
oscillator for reliable operation
• Programmable code protection
• Power saving SLEEP mode
• Selectable oscillator options
• Low power, high speed CMOS FLASH/EEPROM
technology
• Fully static design
• In-Circuit Serial Programming(ICSP) via two
pins
• Single 5V In-Circuit Serial Programming capability
• In-Circuit Debugging via two pins
• Processor read/write access to program memory
• Wide operating voltage range: 2.0V to 5.5V
• High Sink/Source Current: 25 mA
• Commercial, Industrial and Extended temperature
ranges
• Low-power consumption:
- < 0.6 mA typical @ 3V, 4 MHz
- 20 ìA typical @ 3V, 32 kHz
- < 1 ìA typical standby current
THE  ANALOG /DIGITAL CONVERTER using MIKROC PROGRAM
The converter generates a 10-bit binary result using the method of successive approximation and stores the conversion results into the ADC registers (ADRESL and ADRESH )


Circuit Diagram :


 for more information about code contact me :
zouhair_charaf@yahoo.com

Saturday, October 15, 2011

power supply by l7812 & l7805

Description :
embedded systems require electrical power to operate .Most of the compenents in them including the processors can operate at a wide range of voltage 5v that why we need to using regulated constant voltage for safer opration of the embedded system. also we use it for any application that uses analog-digital converters (ADCs).ADCs require a fixed reference voltage to provide accurate digital count for input analog signal .if the referance voltage is not stable, the ADC output is meaningless
so today I will show you hot to make a regulated 12v & 5v power source for our lab
An LM 7812 17805 are linear regulator Ic is used for this purpose ,it converts a DC input voltage of range 7-25v for l7805 & 14-35 for l7812 and every one can delivery 1A current
when a good cooling is added to regulator. the circuit has overload and terminal protection . the capacitor must be enough high voltage rating to safely handle the input voltage feed to circuit.
the parts of a power supply 
figure 1 show you a block diagram of a power supply system which convert a 230v AC into a rtegulated 5v or 12v dc supply
A simple power supply circuit that includes each of these blocks in given in figure 2 .the following articles in this series look at each block of the power supply in detail 
                                                                                                                
you can also to make modification like to remove transofomer & rectification and replace them by adaptor 16v 1A figure 3 show you circuit after change 
for make this project we need to :
adaptor 16v 1A 
diode 1n4001 
capacitor  2 x100uf ; 2x10 uf
7812 & 7805 regulator 1 A
rsistor 230 
led red 

PCB circuit :


Friday, October 14, 2011

pic 16fxxx and software

Tutorial Microcontroller Programming using pic 16Fxxx

Tuesday, October 4, 2011

about me and this blog

hi
My name is charaf zouhair I'm from Morocco ;I'm technical electronics & eletrical I love electronics project that's why I made this blog even to share my small experience with outher people ,student /hobbyist or else in the world , now I'm looking to growing my experience with programming microcontrollers and building fun projects with them
Microcontroller and thier programming devices have now become so cheap and easily accessible that everyone can have his own programmer and development board these days.What they need further is access to gree comprehensive resources on this subject so that they could learn to use microcontrollers on thier iwn
So I hope to enjoy with my blog even to go far with microcontroller programming .

thanks