PWM (Pulse Width Modulation) in Embedded System

After reading this article you will understand :

  1. What is PWM
  2. What is duty cycle , TON and TOFF 
  3. How to calculate TON and TOFF based on duty cycle
  4. How to generate PWM using timers
  5. Applications and need of PWM
  6. Average voltage of PWM wave calculation formula.

1. Introduction to PWM :

Full form of PWM is pulse width modulation, i.e. in PWM width of the pulse is varied by keeping period of pulse constant.

As shown in below image width of pulse is varied but time T is constant.

Fig. 1  PWM Concept

Now lets go into more details. PWM pulse has ON time i.e. TON and OFF time i.e. TOFF. ON time is time for which PWM pulse is high and OFF Time is time for which PWM pulse is low. In PWM we can change time duration of TON or TOFF and hence width of the pulse is varied but period of pulse is constant i.e. T(Period of pulse)= TON+TOFF

Consider PWM pulse with  TON=1 sec and TOFF =1sec. Period of Pulse is TON+TOFF = 1sec +1sec = 2sec. i.e. frequency of PWM pulse is 0.5 Hz

Now you can change TON and TOFF like :
TON  = 1.5 sec and TOFF=0.5 sec  by keeping period of pulse unchanged i.e. T=2sec
TON  = 0.5 sec and TOFF=1   sec.  by keeping period of pulse unchanged i.e. . T=2sec

Fig.2 PWM with TON 1sec and TOFF 1sec

1.1 What is Duty Cycle :

Now variation of TON and TOFF can be measured by duty cycle :
Duty cycle(%)  = (TON/(TON+TOFF))*100
i.e. duty cycle represents, for how much time pulse is high, out of total pulse period.

So ,
50% duty cycle means TON= 1sec    and TOFF = 1sec 
75% duty cycle means TON= 1.5sec  and TOFF = 0.5 sec
25% duty cycle means TON= 0.5 sec and TOFF = 1.5sec

1.2 Calculation of TON and TOFF based on Duty Cycle :

Consider above example, PWM with frequency of 0.5Hz and duty cycle is 10% then 
10% duty cycle means TON is for 10% period and TOFF is for 90% period

i.e.  10%2 sec = 10/100*2 sec = 0.2sec TON
90%2 sec = 90/100*2 sec = 0.8sec TOFF

       TON = 0.2sec and TOFF= 0.8sec

1.3 What is frequency of PWM :

Frequency of PWM is calculated as Fpwm = 1/(TON+TOFF).

2. What is use of PWM :

In previous section you have learnt what  is PWM, duty cycle and frequency of PWM.  In this section we will learn what is use of PWM and what is importance of duty cycle and importance of PWM frequency .

PWM is used to control analog circuit digitally (as PWM is digital)  Now in real life you can control  LED brightness using PWM. But how ? 

Consider Fig.3 which shows a micro-controller connected to LED. PIN to which LED connected is having PWM functionality i.e. output of PIN is PWM. Now we will see how brightness of LED is controlled by PWM.

PWM is digital pulse and lets consider  voltage of PWM is 5V or 0V i.e. digital 1 or digital 0 (Vout of PIN is 5V or 0V). Consider 0% duty cycle, 25% duty cycle,50% duty cycle and 100% duty cycle, as shown in figure 3.

Fig.3  PWM Duty Cycle and Average Output voltage

By applying PWM pulse to LED, an Average Voltage is applied to LED.  Average voltage of PWM wave is shown by dotted line.  Average Voltage : 

Vout(Average Voltage) = Vmax*duty cycle. 
Vmax is 5V (maximum output voltage of MCU Pin)

PWM duty cycle kept as    0%  then Vout (Average Voltage) = 5*0/100      = 0V
PWM duty cycle kept as  25%  then Vout (Average Voltage) = 5*25/100    = 1.25V
PWM duty cycle kept as  50%  then Vout (Average Voltage) = 5*50/100    = 2.5V
PWM duty cycle kept as  75%  then Vout (Average Voltage) = 5*75/100    = 3.7.5V
PWM duty cycle kept as 100% then Vout (Average Voltage) = 5*100/100  = 5V

LED brightness can be controlled using PWM by varying duty cycle i.e. by varying average out voltage.

Consider PWM as switch, for TON , LED will be turn on (as LED will receive 5V) and For TOFF(as LED will receive 0V) LED will be turn off. If you keep TON as 1 sec and TOFF as 1 sec then you will observe ON and OFF of LED. You will never observe LED dimming effect i.e. changing brightness LOW to High, this is due to PWM frequency is low.

To do so, we need to apply PWM pulse to LED with high PWM frequency, so that ON and OFF state of LED will change so fast. So if you change frequency of output pulse and keep it as 1Khz i.e. Period of Pulse is 1ms and duty cycle of PWM is 50%  then for 0.5ms LED will off and 0.5ms LED will be on and this would happen so fast that dimming effect will occur as LED receives only 2.5V

if you change the duty cycle to 10% then LED will have low brightness , as it will be OFF for 90% of time and ON for 10% time.

if you change the duty cycle to 90% then LED will be more brighter, as it will be ON for 90% time and OFF for 10% time.

Similar way you can control motor speed using PWM.

2.1. Why PWM :

By Controlling analog circuit digitally system cost and power goes down.

3. Ways to generate PWM :

1st way : Most of micro-controller manufactures have started providing PWM as peripheral so that it would be easy to generate it. Using PWM peripheral i.e. on pin of micro-controller is set to PWM output, by setting duty cycle and frequency of PWM, MCU will calculate TON and TOFF and generates required PWM pulse on that pin.

2nd way :Also if MCU does not have PWM as peripheral there is a way to generate PWM pulse using timer. If you are not aware about timers the please read timer in embedded system :

how to generate PWM using timer?

  1. Configure 2 timers. 1st timer is for TON and 2nd timer is for TOFF. (Values of TON and TOFF are depends on value of duty cycle and frequency of PWM , as described in above sections)
  2. Start TON timer (with TON time of pulse) once timer reaches to certain time value, stop 1st timer and start 2nd timer (with TOFF time of pulse). This can be done by using ISR of timers. Once timer 1 ISR executed, start Timer 2 and in timer 2 ISR start timer 1
  3. When 1st timer is started. set digital out pin to High (logic 1) and when 2nd timer started set same digital out pin to Low (logic 0).

Watchdog Manager in AUTOSAR

 After reading this article you will learn :

  1. What is role of watchdog manager  in watchdog stack of Autosar
  2. What is Supervised entity, supervision cycle, supervision functions  and check points?
  3. How watchdog manager supervises the SW using Alive indication, Deadline monitoring and Logical supervision.
  4. Watchdog Manager Interfaces with SWC and how to use watchdog  interfaces with SWC.
  5. Important Configuration Parameter of watchdog manager.

1. Introduction to Watchdog Manager:

Watchdog manager (WDGM) present at service layer of AUTOSAR stack as seen in fig.1.
Task of watchdog manager is to supervise software execution and if it finds error or flaw in execution of software, WDGM takes action on it. SWCs uses services provided by WDGM, using client server interface. SWC are client and WDGM is server.

Fig.1 WDGM in AUTOSAR Layered Architecture

2. Functionality of WDGM :

Functionality of WDGM is
  1. To supervise the SW and to supervise software, watchdog manager uses supervised entities.
  2. WDGM can change the mode of WDG driver (Slow, Fast or OFF).
  3. WDGM updates triggering condition in case supervision of SW is OK
  4. If global supervision status is not OK then resets ECU or do not set triggering condition, so that WDG driver will not trigger WDG and WDG will generate reset.

2.1 Supervision and Supervised Entity :

What is supervised entity ?
Supervised entities (SEs) nothing but a runnable within Software Component (SWC), BSW or CDD.

What WDGM supervises ?

WDGM supervises the supervised entities in SWCs and checks if :

1. Supervised entities (in Software) are getting executed periodically as per configuration e.g. if a runnable having frequency of 10ms so in 50ms runnable should have executed 5 times so watchdog manager monitors if SEs are getting executed number of times (e.g. 5) as per configuration 

2. Flow of SE or sequence of execution of SEs are as per design (e.g. code is getting executed in correct sequence).

3. SEs are getting executed within expected time? (e.g. if runnable A should finish its execution in 5ms then WDG manager checks 

What is Checkpoint ?

How WDGM get to know that supervised entity has been executed ? 

Supervised entities uses checkpoint and when checkpoint (i.e. particular area or line in code may be start of runnable, end of runnable or in between some code line of runnable ) is reached while execution, supervised entities notifies to watchdog manager that this checkpoint is reached (i.e. it is executed).

Supervised entities uses port provided by WDGM to notify checkpoint reached, using client server mechanism as shown in fig.1.  Function Provided by WDGM is 

Std_ReturnType WdgM_CheckpointReached ( 
 WdgM_SupervisedEntityIdType SEID,
 WdgM_CheckpointIdType CheckpointID

There can be multiple checkpoint in one runnable or single check point in one runnable that depends on the design and can be configurable.

Watchdog  manager keeps track of check points reached indication and calculates status of supervision  based on supervision function. Status of supervision is calculated in supervision cycle

What is supervision cycle ?

Frequency at which watchdog manger supervises supervised entities . e.g. if supervision cycle is configured as 50ms then every 50ms watchdog manager supervises the supervised entities and  checks the status of supervised entities as per configuration.

Putting it all together :

Refer fig.2 , which shows SWCs their runnable and supervised entities.

Fig.2 SWC to WDGM connection

In a system there are multiple runnable and  among them if 2 are selected as supervised entities.
Supervision cycle of WDGM is configured to 50ms. 
cyclicity of SE1 is 5ms and cyclicity of SE2 is 10ms.

Every 5ms SE1 and every 10ms SE2 will indicates checkpoint reached to WDGM i.e. indicates to WDG,  particular line(or area) in code is reached.

Every 100ms WDGM will calculate the status of SEs based on checkpoints reported by SEs and supervision function, decides if status of SE is correct or incorrect. 

WDGM calculates local supervision status based on status of supervision of each SE in system. Based on local supervision status WDGM calculates Global supervision status and decides SW execution is OK or not.

2.2  WDG Triggering :

WDGM is no longer responsible for triggering the WDG driver since AUTOSAR version 4, WDGM sets a flag in software to true or false i.e. sets triggering condition to TRUE or FALSE based on Global supervision status. WDGM uses function WdgIf_SetTriggerConditionto() update a flag.

WDG driver reads the flag i.e. triggering condition and based on triggering condition (if TRUE) triggers the watchdog to avoid reset. 

3. Supervision Functions and working :

In above section you have learnt that WDGM supervises supervised entities by using supervision functions. WDGM performs this task in every supervision cycle and supervised entities reports their status by using checkpoint reached functionality (WdgM_CheckpointReached) to WDGM. WDGM calculates status of supervision based on supervision functions and these supervision functions are :

3.1 Alive indication : 

To check if SEs are alive and getting executed number of times in one supervision cycle. This will help to monitor execution of SEs, helps to check if  SE is getting executed too many time or getting executed less time. For alive indication 1 checkpoint in each SE will be required. 
i.e.  Alive supervision is check for cyclic timing constraint.


void cyclicRunnable_10ms() 
	/*perform some action every 10ms*/


void cyclicRunnable_5ms() 
	/*perform some action every 5ms*/

void cyclicRunnable_20ms() 
	/*perform some action every 20ms*/

  • In a system (refer above code snippet) there are multiple runnable. 
  • 3 runnable are selected as Supervised entitiesSE1 (5ms), SE2(10ms),SE3(20ms). 
  • At time of execution , SE will notify checkpoint reached to WDGM using RTE.
  • In supervision cycle (WdgMSupervisionReferenceCycle)100ms WDGM will build the status of alive indications.
  • WDGM will calculate number of alive indications reported by SEs
  • We can add + and - (minimum tolerance :WdgmMinMargine and maximum tolerance :WdgmMaxMargine) tolerance to expected indications.
  • WDGM will verify it against expected alive indications (WdgMExpectedAliveIndications) and calculates local supervision status of each SE 
  • Expected alive indications for SE1: 20+WdgmMaxMargine or 20-WdgmMinMargine 
  • Expected alive indications forSE2 : 10+WdgmMaxMargine or 10-WdgmMinMargine
  • Expected alive indications forSE3 : 5+WdgmMaxMargine or 5-WdgmMinMargine
  • If expected indications match then all SE are executing as per design.
  • Else SE are not executing as per design
  • Based on this WDGM will calculate status of SE's supervision as correct/incorrect.

3.2 Deadline monitoring : 

To check if SEs (non cyclic) are finishing their execution in expected time. For this 2 checkpoints are required in SEs and WDGM calculates time of between two checkpoint to determine the execution time of SE. Execution time span can have minimum (WdgMDeadlineMin) and maximum deadline (WdgMDeadlineMax) for execution.

void InitDio()

  RteCall_WdgM_CheckpointReached(SE4_ID,CP_ID_4); // Report Checkpoint 1 Reached 

   PINSEL2 = 0x000000;  //Configure the P1 Pins for GPIO
   IODIR1 = 0xffffffff; //Configure the P1 pins as OUTPU

  RteCall_WdgM_CheckpointReached(SE4_ID,CP_ID_5); //Report Checkpoint 2 Reached  

  • A non cyclic supervised entity (InitDio) to be supervised using deadline monitoring.
  • SE will finish execution within : WdgMDeadlineMin : 4ms and WdgMDeadlineMin :6ms
  • SE will require minimum two checkpoints for deadline monitoring.
  • WDGM will calculate time between 1st and last checkpoint.
  • At Start of 1st checkpoint i.e. CP4 in above code snippet  (WdgMDeadlineStartRef) WDGM will note the time stamp
  • And at last  checkpoint i.e. CP5 in above code snippet  (WdgMDeadlineEndRef) WDGM will note the time stamp
  • WDGM calculate time of execution of SE by calculating difference between last check point and first checkpoint.
  • WDGM will verify calculated time  against expected time i.e. it should be between  W 
  • WDGM will calculate status of SE's supervision as correct/incorrect.

3.3 Logical supervision : 

Logical Supervision checks if the code of Supervised Entities is executed in the correct sequence.
In Logical supervision n number of checkpoints used. 

As you are aware while designing the code we are using flow charts, and based on flow charts we are writing the code. Now logical supervision will help to verify the flow chart i.e. logic written in code is as per design or not, hence it is called logical supervision.

As per the flow chart, we can decide the checkpoints. These checkpoints will form a graph
Refer below snippet, a code is given and as per logic checkpoints are added.

void cyclicRunnable_10ms() 
	Rte_Call_WdgMCheckpointReached(SE1_ID,CP_ID_1); // Checkpoint 1
	Rte_Call_WdgMCheckpointReached(SE1_ID,CP_ID_5); // Checkpoint 5


void readVolatage() 
	Rte_Call_WdgMCheckpointReached(SE2_ID,CP_ID_2); // Checkpoint 2	

void processVoltage() 
	if(voltage >10)
		Rte_Call_WdgMCheckpointReached(SE3_ID,CP_ID_3); // Checkpoint 3
		Rte_Call_WdgMCheckpointReached(SE3_ID,CP_ID_4); // Checkpoint 4
clearError(); } }

  • WDGM checks if transition of checkpoints are as expected (i.e. as per logic designed).
  • Expected Transitions :   CP1-->CP2-->CP3-->CP5-->CP1
  • Expected Transitions :   CP1-->CP2-->CP4-->CP5-->CP1
  • WDGM has  Activity Flag for each graph, initialized to FALSE
  • Activity flag helps to decide if checkpoint reported is 1st checkpoint or not.
  • Supervised entities will notify checkpoint reached to WGM e.g. CP1 in fig.4 
  • WDGM will store current checkpoint and set Activity flag toTRUE
  • When next checkpoint is reported (CP2) WDGM will store it and check with previous checkpoint (CP1). WDGM checks if this transition (CP1-->CP2) is valid or not if activity flag is TRUE.
  • Similarly WDGM will check transition from CP2-->CP3 is valid or not
  • WDGM checks the flow of execution.
  • If CP1 is reported and then CP4 is reported, then this is not valid transition and WDGM will update status of SE's supervision as correct/incorrect.

From above discussion it is clear that WDGM calculates status of supervision of SE as correct/incorrect based on supervision function. Based on status of each supervision of SE (correct/incorrect), WDGM builds local status of supervision and based on local status WDGM calculates Global Status of supervision.

4. Important Configuration Parameters :

You want to configure WDGM, below are the some points you should always keep in mind to configure :

1. Define Supervised entities and Supervised entity IDs
2. Define Checkpoints of Supervised entities and checkpoint IDs
3. Select supervision Function to be used : Alive/Deadline/Logical. Configure values to below parameters as per supervision function selected
  • Alive Supervision : WdgMExpectedAliveIndications
  • Alive Supervision : WdgMMaxMargin
  • Alive Supervision : WdgMMinMargin
  • Alive Supervision : WdgMSupervisionReferenceCycle i.e. supervision cycle
  • Alive Supervision : WdgMFailedAliveSupervisionRefCycleTol (accepted failed count of supervision of SE, used in local supervision status calculation)

  • Deadline Supervision : WdgMDeadlineStartRef
  • Deadline Supervision : WdgMDeadlineEndRef
  • Deadline Supervision : WdgMDeadlineMin
  • Deadline Supervision : WdgMDeadlineMax
  • Deadline Supervision reference cycle i.e. supervision cycle 
  • Deadline Supervision : WdgMFailedDeadlineRefCycleTol

  • Program Flow reference cycle i.e. supervision cycle
  • Program Flow : WdgMFailedProgramflowRefCycleTol
4. Define WDGM Initial mode : Slow or Fast
5. Define WDGM Slow mode (1000ms) and Fast Mode(200ms) timings.
6. Define WdgMExpiredSupervisionCycleTol (accepted failure count of local supervision, used in Global supervision status calculation)
7. OS Application reference.

Watchdog Driver in AUTOSAR

After reading  this article you will learn :

  1. Use of watchdog driver.
  2. Fast Mode, Slow Mode and OFF mode of watchdog.
  3. Triggering of Watchdog (Internal/External)
  4. Important configuration parameters for Watchdog.

1. Introduction to Watchdog Driver :

Watchdog driver present in MCAL layer of AUTOSAR. Main use of watchdog driver is to trigger HW watchdog.

Watchdog driver is used to initialize HW watchdog, trigger the watchdog and to change the mode of watchdog(Slow/Fast/OFF).

If internal watchdog (internal to MCU) is not used and external watchdog is used (external to MCU),then driver for external watchdog present in onboard abstraction layer (ECU Abstraction) and this driver needs other MCAL driver (e.g. SPI) to communicate  with external watchdog.

Fig.1 AUTOSAR Watchdog Stack

Fig 1. Shows location of watchdog driver in AUTOSAR stack, it shows internal as well as external watchdog driver. If you are not aware about what is watchdog then please read blog about watchdog.If you are aware about watchdog concept, then in next chapter we will see how watchdog functionality is used in AUTOSAR.

2. AUTOSAR Watchdog Concepts :

Watchdog has its counter, when system starts and wdg is initialized (Wdg_Init () functin provided by AUTOSAR watchdog driver to initialise HW watchdog driver) this counter starts counting from 0.When count reaches to particular count (watchdog timeout period), watchdog will generate reset. To avoid reset, SW need to trigger watchdog before watchdog count reaches to certain value.

e.g Watchdog timeout period is configured as 100ms. 

Clock to watchdog is 1Khz.

1 tick of clock = 1ms

watchdog counter will starts with 0 and when it reaches to 100 i.e. 100ms is over and SW did not trigger the watchdog and watchdog will generate reset.

2.1 What is Slow Mode, Fast Mode and OFF Mode :

  • Slow mode means timeout of watchdog is high e.g 1000ms (Generally used at system startup) 
  • Fast mode means timeout of watchdog is low e.g. 100ms (Generally used at run time)
  • OFF mode means watchdog functionality is OFF. (if WdgDisableAllowed is configured to true)
While configuration of Watchdog driver you can decide what should be the init mode(slow/fast).Later at run time watchdog manager changes the mode(slow/fast) as per configuration. Wdg_SetMode() is the function provided by watchdog driver.

2.2 How to trigger Watchdog at right time? 

To trigger watchdog at correct time, in AUTOSAR it is mentioned that use GPT timer service. e.g. if you want to trigger watchdog at 60ms, then configure GPT timer for 60ms and use GPT interrupt (ISR) mechanism to trigger the watchdog at particular time.

Note : Start GPT timer immediately after WDG is triggered.

e.g. if watchdog timeout period is 100ms and you want to trigger watchdog every 75ms then configure GPT timer for 75 ms. Now once WDG driver is initialized and trigger is provided to internal/external watchdog (i.e. WDG counter starts from counting 0), immediately after this start  GPT timer.

Trigger to external watchdog can be done by Spi/Dio.

Triggering Condition :

As mentioned in above section, trigger watchdog by using GPT services (ISR), but while triggering watchdog , triggering condition should be considered. Triggering condition is updated by Watchdog Manager. If triggering condition is set (i.e trigger counter>0)  then trigger HW watchdog else do not trigger the watchdog (this will leads watchdog counter overflow and generate watchdog reset).  i.e. watchdog manager sets triggering condition and based on that watchdog driver decides to trigger watchdog or not. 

Wdg_SetTriggerCondition(timeout) function provided by watchdog driver to set triggering condition/ trigger counter counter as provided by watchdog manager (it could be 0 or > 0).

Fig.2 Triggering Watchdog

Consider above image provided by Autosar WDG SWS (4.2.2), 

  1. Here it is shown sequence for watchdog triggering. Watchdog manager sets triggering condition based on supervision performed by watchdog manager.
  2. Once interrupt occurred (i.e. GPT interrupt), based on trigger condition WDG driver either triggers watchdog HW or do not trigger HW watchdog.
  3. External watchdog triggering is performed by SPI/DIO driver.

3. Important Configuration Parameters :

While configuration of Watchdog Driver please note below parameters

  1. Watchdog Clock reference :Clock to watchdog
  2. Initial/Default Watchdog Mode : Slow or Fast Mode or OFF
  3. Slow mode timeout : WDG timeout in case slow mode
  4. Fast Mode timeout :WDG timeout in case fast mode
  5. Initial timeout : Default/initial WDG timeout
  6. Disabling of WDG allowed : WdgDisableAllowed
  7. For external WDG provide reference to external module (a DioChannelGroup container in case the hardware watchdog is connected via DIO pins - an SpiSequenceConfiguration container in case the watchdog hardware is accessed via SPI)
  8. If Watchdog is external (e.g. SBC) then configure SPI/DIO (as per need) and configure SBC WDG setting as per SBC watchdog data sheet.

Watchdog Stack in AUTOSAR

 After reading this article you will understand :

  1. Layered watchdog stack in Autosar
  2. Basic functionality of each module of WDG stack.

1. Layered Watchdog Stack :

Fig.1 AUTOSAR Watchdog Stack

Fig.1 Shows watchdog stack in AUTOSAR. Watchdog stack divided into 3 layers. 

Service Layer              : Watchdog Manager (WdgM)
ECU abstraction layer : Watchdog Interface (WdgIf)
MCAL Layer               : Watchdog Driver.    (WDG)

Software components will use service port provided by watchdog manager and communicate with WdgM by client server interface through RTE.

WdgM connected to WdgIf and WdgIf connected to WDG, this is how Watchdog stack control flow happens. Lets see functionality of each module in briefly.

2. Functionalities :

2.1 Watchdog Manager :

Watchdog manager, present at service layer of AUTOSAR stack. Watchdog manager is near to RTE. 
For software components to use Watchdog  services. it can be done by communicating with watchdog manager only.

Functionalities of watchdog manager :
1. Supervising the software, using supervision function.
2. If result of supervision of SW is OK then update triggering condition by calling WdgIf_SetTriggerCondition  function.
If supervision of SW is wrong then WdgM will not update triggering condition and this will leads to reset of SW due to Watchdog reset.
3. To provide functionalities to Software components by using service ports.

2.2 Watchdog Interface :

Watchdog interface present at ECU abstraction layer.  Job of watchdog interface layer is to pass commands/data/call flow from watchdog manager to underlying watchdog driver. 

There could be multiple watchdog driver present in system (internal or external).
Job of WdgIf is to route the request from WdgM to respective WDG driver unit.

2.3 Watchdog Driver :

Watchdog driver resides in MCAL layer of AUTOSAR. This module is responsible for direct hardware access. 

Watchdog driver can be internal or external. Internal Watchdog is present  inside controller. External watchdog is external to microcontroller, i.e. separate chip's watchdog  is used (SBC). SBC watchdog can be controlled using SPI/I2C driver. as shown in figure 1.

Main function of watchdog driver is to kick/trigger the HW watchdog unit based on triggering condition set by WdgM module. 

WDG driver modules job is to configure HW watchdog by writing values into HW resistors i.e. initialization of WDG and changing the mode of watchdog(fast/slow/off). 
WDG driver provides functionality to window watchdog.

For more details of each module please read below blogs :

Embedded System || Introduction || Lesson-1

In this blog we will see
1. what is embedded system
2. Blocks of embedded system
3. Application domain of embedded system with example.

1. What is embedded system ?

Embedded means "Hidden Inside". What is embedded system ?

Embedded system, is a system of hardware and software is embedded into a larger system.

(e.g. washing machine is larger system containing mechanical parts and to perform functionalities of washing machine a electronic system of hardware and software is embedded into it, which will control larger system)

Embedded system is designed to perform a specific taskse.g. Embedded system present in Washing machine designed to perform tasks related to washing cloths only, it will not perform task of Digital Camera.

Embedded can be independent system e.g. digital calculator or part of larger system e.g. car having different embedded systems like one for controlling headlight or one for window control.

1.1 How does embedded system performs dedicated tasks ?

To perform dedicated task, embedded system uses a Micro-controller or micro-processor, piece of code is present inside micro-controller or micro-processor i.e. Embedded Software, this software is nothing but set of instructions to micro-controller or micro-processor to perform a task by controlling hardware. (Refer fig.1)

Embedded software contains logic to perform a task. Embedded  software is written by using Embedded C language. e.g. in case of washing machine, software has logic to perform task of washing clothes, if you press button start washing machine will start cleaning clothes.

Note : Micro-controller or micro-processois main processing unit of embedded system. 

Fig. 1 Embedded System

1.2 Application Areas of Embedded System :

Where embedded system is used in this world, Embedded system is used in many fields such as :

1. Medical : Health Monitoring devices e.g a device  (embedded system) which has a dedicated task to monitor patients heart rate and display it on screen.

2. Home Appliances : Embedded system is present in micro-wave oven which is designed to perform tasks related to heating the food.

3. Automotive : Many embedded systems are present in car e.g. Headlight control unit which is designed to control headlight based on inputs given by user with the help of switch. HAs dedicated tasks related to Turn ON/OFF headlights.

4. Aerospace : Many embedded systems are present in Airplane.  Embedded system is used to control engines of Airplane or another embedded system has dedicated task of control of wheels of airplane or shows position of aircraft.

5.Consumer Electronics : Embedded system used inside of digital camera, which has dedicated tasks related to click photos.

Fig.2 Embedded System Application Domains

2.  General View of an Embedded System :

Fig.3 Shows general view of an Embedded system. Important blocks of embedded system are :

1. Input : Inputs required in embedded system to provide user request (e.g. in case of Digital camera, a button to click photo) inputs to embedded system are connected to micro-controller / micro-processor based on inputs embedded system will perform some action (embedded software present inside Digital Camera will take a photo and save it in memory) this is output part of embedded system.

Inputs are provided from Sensors.

2. Outputs : Outputs are actions based on inputs, e.g. control of motor in case of washing machine or LED on-off  in bike headlamp. Actions are performed by embedded software.

Outputs are provided in form of an action.
Also it may be provided on screen as a feedback to user.

Fig. 3 General View of an Embedded system

3. Hardware Components : Hardware components are important part of embedded system. Main part of hardware is Micro-controller/ Micro-processor rest hardware is build around it. e.g. Sensors (to provide input), motors or LEDs (for output), LCD screen, switches, power supply, also electronic components like  diode, resistors, capacitor...etc

4. Software Component : Software components are brain of embedded system. Logic of task is defined in software component i.e. for input X perform action Y e.g. lets consider headlamp control unit , if switch is ON then turn Headlamp ON. Software is present inside micro-controller or micro-processor.

e.g Consider a washing machine, user of washing machine will press buttons present on washing machine to select water level, wash cycle and spin cycle, these buttons are connected to micro-controller or micro-processor and provides input to micro-controller or micro-processor. 

Based on inputs, software inside micro-controller or micro-processor, will calculate washing time and take action (filling water in machine, washing and drying clothes) and control other hardware part, such as motor to rotate drum and dry the clothes within time and displays information on screen and plays sound to indicate task (washing clothes) is done  i.e. output. 

4. Summary :

In this lesson you have learnt about what is embedded system, structure of embedded system, application domains and hardware-software part of embedded system. In next lesson we will discuss about micro-controllers.

Practical Embedded C || Preprocessor Directive || Chapter 2

In this blog you will learn what is Preprocessor Directives in Embedded C using LPC1768.

1. What is preprocessor Directive :

The first stage of C code compilation phase is preprocessing. Preprocessor scans the code, modify it and gives to compiler stage. C Preprocessor directives are commands to Preprocessor, Preprocessor directives starts with symbol #.

Preprocessor scans the code and look for token #, when # encounters preprocessor takes action to  based on preprocessor directive and modifies souce code.Modified source will not contain any preprocessor directive (starts with #) and this code without Preprocessor directive is given to compiler for compilation. 

The `#' is followed by an identifier that is the directive name.The set of valid directive names is fixed. Programs cannot define new preprocessing directives.

Note : There is no semicolon at end of preprocessor directive and multi line preprocessor directive uses " \" back slash.

2. Functionalities of Preprocessor Directives :

Below are the some functionalities of Preprocessor Directives used in embedded system

2.1. To include files :

To include files preprocessor directive used is #include. 

#include<filename.h> : Includes file from Standard directory. Stand directory path is defined in IDE.

#include "filename.h" : Includes file from current directory where respective source files is present  and if it does not found file in current directory then preprocessor searches file in standard directory and includes from there.

Preprocessor will find #include as command and includes a file's contents in C source code
e.g. #include<stdio.h>.  in C you have used this.

In embedded C, micro-controller specific header files are included. Consider example of LPC1768, device header file is lpc17xx.h and ARM CORTEX M3 related file is core_cm3.h so while programming you have to include below files :

#include <lpc17xx.h> 
#include <core_cm3.h> /*Cortex M3 architecture related content*/

void main()


 /*Kept empty to explain #include*/


After Preprocessing :

After Preprocessing Contents from header files will be added to source file, it will look like this :
There are more lines but for example few lines are shown below

Part of content from lpc17xx.h :
typedef struct
  volatile uint32_t SPCR;
  volatile const uint32_t SPSR;
  volatile uint32_t SPDR;
  volatile uint32_t SPCCR;
  uint32_t RESERVED0[3];
  volatile uint32_t SPINT;
} LPC_SPI_TypeDef;

Part of content from  core_m3.h :

typedef struct
  volatile uint32_t CTRL;
  volatile uint32_t LOAD;
  volatile uint32_t VAL;
  volatile const uint32_t CALIB;
} SysTick_Type;

void main()



2.2. To perform conditional compilation : 

In conditional compilation using preprocessor directive, particular section of code is selected using preprocessing Directive, and that selected code will be compiled.

Conditional compilation is required
1. A program may need to use different code depending on the machine or operating system it is to run on. So these will a conditional compilation Preprocessor directive.
2. You may want to be able to compile the same source file into two different programs
3. A conditional whose condition is always false is a good way to exclude code from the program but keep it as a sort of comment for future reference.

For these purpose Preprocessor Directives used are#if #else  #elsif  #ifdefined #ifndef, but remember to use #endif at end. It is similar as if else control structure.       

Below code snippet shows use of conditional compilation. If condition is true code will be part of source file after preprocessor else it will be excluded.

In lpc176xx.h file __Vendor_SysTickConfig     is defined as
#define __Vendor_SysTickConfig    0

as  __Vendor_SysTickConfig     is 0 below part of code will be compiled i.e. below code snippet will be part of source code after preprocessing.

#if (!defined (__Vendor_SysTickConfig)) || (__Vendor_SysTickConfig == 0)

static __INLINE uint32_t SysTick_Config(uint32_t ticks)
  if (ticks > SysTick_LOAD_RELOAD_Msk)  return (1);            /* Reload value impossible */
  SysTick->LOAD  = (ticks & SysTick_LOAD_RELOAD_Msk) - 1;      /* set reload register */
  NVIC_SetPriority (SysTick_IRQn, (1<<__NVIC_PRIO_BITS) - 1);  /* set Priority for Cortex-M0 System Interrupts */
  SysTick->VAL   = 0;                                          /* Load the SysTick Counter Value */
  SysTick->CTRL  = SysTick_CTRL_CLKSOURCE_Msk | 
     SysTick_CTRL_TICKINT_Msk   | 
     SysTick_CTRL_ENABLE_Msk;                    /* Enable SysTick IRQ and SysTick Timer */
  return (0);                                                  /* Function successful */


Conside below example.  __CM3_REV is not defined

typedef struct
       uint32_t RESERVED0;
  __I  uint32_t ICTR;                         /*!< Offset: 0x04  Interrupt Control Type Register */
#if ((defined __CM3_REV) && (__CM3_REV >= 0x200))
  __IO uint32_t ACTLR;                        /*!< Offset: 0x08  Auxiliary Control Register      */
       uint32_t RESERVED1;
} InterruptType_Type;

After Preprocessing
stage ACTLR will not be part of structure i.e will not be part of  source code, as shown in below code snippet.

typedef struct
       uint32_t RESERVED0;
       volatile const uint32_t ICTR;

       uint32_t RESERVED1;

} InterruptType_Type;

Similarly piece of code can be part of compilation based on conditional compilation preprocessor directive.

2.3. Macros Expansion :

Macros are used to give symbolic names. Macro is name given to piece of code, when Macros appears in code pre-processor will copy contents of macro (defined by programmer) and replace it in source file.

Syntax : #define  Macro_Name   Macro_defination
e.g. #define ARRAY_SIZE 5 
This is macro and when ARRAY_SIZE is encountered in C source code at time of preprocessing, preprocessor will replace ARRAY_SIZE with 5 in code.

Now we will see how macros are used in Embedded C . Consider case of LPC 1768, in lpc17xx.h file you can find ADC structure is defined like :

typedef struct
  __IO uint32_t ADCR;
  __IO uint32_t ADGDR;
       uint32_t RESERVED0;
  __IO uint32_t ADINTEN;
  __I  uint32_t ADDR0;
  __I  uint32_t ADDR1;
  __I  uint32_t ADDR2;
  __I  uint32_t ADDR3;
  __I  uint32_t ADDR4;
  __I  uint32_t ADDR5;
  __I  uint32_t ADDR6;
  __I  uint32_t ADDR7;
  __I  uint32_t ADSTAT;
  __IO uint32_t ADTRM;
} LPC_ADC_TypeDef

Some other MACROS as :

#define LPC_APB0_BASE         (0x40000000UL)
#define LPC_ADC_BASE          (LPC_APB0_BASE + 0x34000)
#define LPC_ADC                       ((LPC_ADC_TypeDef       *) LPC_ADC_BASE      )

e.g. Consider below code snippet. LPC_ADC.ADCR is used in main function. LPC_ADC.ADCR is defined in lpc17xx.h file as shown in above code snippet.

#include "lpc17xx.h"
#include "core_cm3.h"

void main()
 LPC_ADC.ADCR = 0x00;

After preprocessing LCP_ADC is replaced with MACRO definition defined in header file
Note : Header file expansion is not shown below it is  explained in 2.1
After preprocesssing source code of main function look like :

void main()
 ((LPC_ADC_TypeDef *) ((0x40000000UL) + 0x34000) ).ADCR = 0x00;

2.4. Error Reporting :

Error reporting is used in case of debugging, #error  displays fatal error.

Below snippet shows #error preprocessor.  If CLKSRCSEL_Val is not in range then error will thrown out at compilation time.

#if (CHECK_RANGE((CLKSRCSEL_Val), 0, 2))
   #error "CLKSRCSEL: Value out of range!"

This is how Preprocessor Directives are used in Embeddded system using Embedded C.

Practical Embedded C || Introduction || Chapter 1

Welcome to Practical Embedded C series. In this series we will learn how embedded C is used in embedded system along with basics of topic (e.g. you will learn basics of pointers as well as how pointers are used in embedded system). ARM cortex M3 (LPC 176X) micro-controller is considered for reference to explain Embedded C topics throughout the series.

1. What is Embedded C ?

You all must be aware of that C language is developed by Dennis Ritchie in early 1970s. Embedded C is an extension of the standard C language.  This extension is to support the features required for embedded software development which are missing from C language and these are :

1. Fixed Point Arithmetic : C language does not support Fixed point arithmetic. Embedded C
supports fixed point arithmetic by adding _Fract and _Accum  keywords and saturating fixed point type Specifier _Sat.  For this <stdfix.h> header file is used.

2. Named Address Spaces : C language supports  generic or linear address space. Embedded C supports Named Address Space.  Address Space nothing but different  memory regions. Micro-controllers have different memory areas and embedded  applications uses them e.g. a memory area for GPIO or  memory area for code and constants.

If an implementation provides intrinsic address spaces with names _X the following are valid declarations:

_X char varible_char;

3  Named Storage Registers : Using Embedded C it is possible to access processor resistors that are not addressable in any of the address space.

Assuming _DP and _CC are the names of intrinsic registers, the following are possible valid declarations:
 register _DP volatile unsigned char direct_page_reg;

4. IO Hardware Addressing : Embedded C supports IO registers, using which we can access IO devices e.g. LDC. 

Embedded C is used for development of micro-controller based programs. Embedded C uses libraries ( header files) to access micro-controllers registers or memory or peripherals. Library files depends on micro-controller and changes micro-controller to micro-controller.

2. Why Embedded C?

Initially to program micro-processors Assembly language was used, but assembly is bit difficult to understand and debugging is also difficult in Assembly language. As processor architecture to architecture Assembly instruction changes to it is difficult to make program portable in assembly language. 

To overcome these difficulties C languages used. C is easy to understand and debugging is easy, also codes can be made portable from platform to platform using C language.

3. Structure of  Embedded C Program :

In this section you will learn what is structure of embedded C program. The structure is same of C program,but while including header files, micro-controller specific files are included. And inside main function micro-controller related resistors are accessed as per features defined in point 1 (described above in this blog).

#include <lpc17xx.h> /*Micro-controller specific header file*/

#define SBIT_RESULT 4u /*Macro Declaration*/

int main()
unsigned char adc_result ; /*local variable declarations*/
LPC_PINCON->PINSEL1|= 0x01<<14; /* Select the P0_23 AD0[0] for ADC function */

   LPC_ADC->ADCR |= 0x01;
Some Code lines
adc_result = (LPC_ADC->ADGDR >> SBIT_RESULT) & 0xfff;
return 0;