Friday, October 26, 2012

Multiprogramming in Embedded Software

SA,..
I know this is pretty long topic, and discussed heavily while writing multi-threaded applications for desktop, but I have found few books that tackle that subject in Embedded Software. I will also review some basic operating system concepts, that can be found in any real time operating system book.

Embedded Systems Architecture

The minimum software architecture to construct a simple embedded system or even fifa2012 is the following code:

for games, the game ends when the user quits the game by himself
while(!exit)
{
render_graphics();
updateAI();
updatePhysics();
}
The same for an Embdded System, except that the system will exit or shutdown when the user switches off the power.
while(1)
{
readAdc();
calculateWeight();
sendtoPC();
}
This is AKA endless loop, and in games it's called Game Loop.
For Embedded Systems, that basic architecture is simple, efficient (no need for timers or other uC resources). On the other hand, if your application requires to read an ADC data precisely for example 2ms, that architecture won't provide you with the flexibility or the accuracy for that task.
Another issue, that the uC will be busy all the time and it will use it's full power, and that have a dramatic impact on the power consumption, especially if you run your system using batteries...

Basically, you need a scheduler to solve the previous issues.    

Basic  OS Concepts

I remember when I got my hands on windows 98, and I finally managed to play, and was surprised by the computer tech-guy while explaining to me how nice was windows98 that it can play Fifa98, and at the same time you can listen to win-amp. It was interesting feature of the windows series, as the previous operating system, windows 3.11,  it didn't support multi-tasking. 

Scheduling is the method that let processes control the cpu time or its working power. By letting the CPU to switch among the processes like a game or windows media player, it can let the computer be more productive. In a comptuer which has only a single CPU, it can only run one process at a time, like a weight a scale, it only can read the weight from the load cell,..etc. The idea of multi-tasking or multi-threaded applications is to have some process running at all times, in order to utilize the full speed of the CPU at max. The basic idea to achieve that, is to execute the process until it waits for a completion of an I/O request. In a simple system like a small embedded system, the CPU just sits idle, and all that time waiting for an I/O Completion is wasted. Most OSs, several processes are kept in memory at one time, when a process in a wait condition, the OS let the CPU to switch to another process. That previous selection process is a property of a CPU Scheduler.

There are two different types of CPU Scheduling 
1. Non-Preemptive Scheduling, once the CPU has been allocated to a process, the process keeps the CPU until it releases the CPU either by terminating (ESC) or by switching to the waiting state (ALT-TAB ;) ). This scheduling method was used by windows 3.1. It provides a single tasking system architecture. 

2 Preemptive Scheduling,  scheduling is prioritized. The highest priority process should always be the process that is currently utilized by the CPU, Windows 95,98..etc works by that technique. it provides a Multitasking system Architecture.

There are different scheduling algorithms like round-robin, you can read more about them at any OS Book.

Next blog isA, will discuss Critical Sections, and issues in multi-tasking, and form a design pattern for that.

Wednesday, October 24, 2012

Design Patterns for Embedded Software (1)



SA..

Introduction

Design patterns is a group of  reusable solutions for problems that appear in software design. Those solutions commonly appear while writing high level object-oriented software for a desktop. A great book that is usually called gang of four book is Design Patterns: Elements of Reusable Object-Oriented Software, it explains design patterns in details .

Commonly, It is very rare to work with objects oriented programming while writing a firmware, however there are c++ compilers available like IAR C/C++ Compiler. I have searched also for resources for commonly design patterns for embedded software and I only found one book that explains design patterns for embedded software, and he tried to mix Gang of Four Patterns, like observer, strategy pattern,..etc and tried to give them the taste for firmware. The book is Design Patterns for Embedded Systems in C: An Embedded Software Engineering Toolkit . The book is really bad and I didn't like it at all, considering using UML for C Code is awful.

1. Polled Input Pattern

The first pattern that I would like to discuss is the Polled Input. Sometimes when you try to read an input from a switch for example, you try to poll switch for reading by a loop like that while(switchInput!=0);   This means the microcontroller will stuck here waiting for the switch to be at ground. This kind of reading an input, is okey for not real time or time triggered embedded systems, you would better utilize an ISR(Interrupt Service Routine) that keeps checking the sensor falling or rising edge, but as you know it will let the CPU to stop it's current task and then completes the ISR. This kind of  Context Switching is an overhead, and rises serious complications in embedded systems. 

The Pattern that solves that should have the following properties:
1. In a real time operating system, or any scheduler  a period task should poll the input for the occurence of the event
2.The period of the  task should Ttask should be <= min Tevent.
Suppose you would like to poll a push button as shown in the following figure with a pull up resistor 10k and VCC. A common problem for push-button or any switch is the residual frequencies due to mechanics, and you need to filter and "debounce" them. Of course you can use the electronics way of filtering the noise, and that's called a hardware filtering and of course the easier way is use Software for filtering those spikes.
Following figure, shows the spikes from pushing on/off a switch.

A simple code that shows the pattern idea



Note that the previous update function should be run in a task scheduler or timer  for example every 50ms to 500ms. Note it also solves the debouching issue with switches.

Saturday, October 6, 2012

In the beginning there was a pixel..

Quoting from the bible JN1-1, it all started with plotting a pixel on the screen. If have you managed to draw a pixel on the screen, then you can write Fifa2012 on your microcontroller, of course on a high specs one :).
By drawing a pixel on the screen, you can use bresenham's line algorithm to draw a line, then you can draw a triangle, then a polygon that is simplified of many triangles, texture, shade, and light it. A great outdated, but still useful resource for all these algorithms is that  Book : Computer Graphics, Principles and Practice, Foley, Vandam.

One of the first game consoles that tried to 3D Software Rasterization is the 3DO Console. It has an ARM6 32bit, clocked by 12.5MHz!!. For Embedded guys, I'm sure you will be surprised about how the low were the specs, and how beautiful games were made on that console and now we a smaller, lower power, faster microcontrollers like PIC32.. 3DO Specs
Anyway,
How can we draw a frame of NTSC Signal ?

The pseudo-code for the algorithm is simple:

1. Draw 8 scan lines  // top over scan
2. Draw 240 scan lines // the active video
3. Draw 10 scan lines // bottom over scan
4. Generate VSync pulse // send the sync pulse to redraw
5. Delay 6 scan lines 

A nice atmel application note for AVR for generating NTSC signals can be found here:
http://www.atmel.com/Images/mega163_3_04.pdf
 

Sunday, September 30, 2012

The Dark Age of Video Games Machines

I remember playing the Sega 16bit game console Mortal Kombat, and I was amazed by how different characters animate on the screen and how on earth my joystick controls some pictures which are just some dead bitmaps on the screen. It all happens by "playing' with the TV or the monitor's electron gun on the phosphoric screen.




                             Mortal Kombat on 8 bit devices and Mortal Kombat on an XBox
Now we have a dedicated GPU (Graphics Processing Unit), and they are programmable, you can write some programs called shaders for them, you can perform complex computations, and simulating complex systems. Note that a GPU is simple a video generator : ). We also now have special APIs that access them easily like OpenGL, DirectX,..etc.

How a GPU Generates Signals?! 

Current GPUs are capable of generating advanced video formats like VGA, HDMI,..etc.
In early video game consoles or VHS or whatever any video device, just use a basic concept that the image is painted on the screen line by line. Referring to the next figure, the video devices basically paints the image from top left of the screen and moving horizontally to the right edge, then moves again to the next line which is shown in grey, then again does the same zig-zag motion, until the screen has been scanned. This process is repeated and it is known as Refresh Rate Hz, which the number of times the screen has been scanned in seconds, I'm sure you have seen that term frequently :).  On the other hand, a Frame is constructed from a complete scanning process. There are different scanning techniques like Progressive Scanning and interlaced scanning  You can read more about both here : http://en.wikipedia.org/wiki/Progressive_scan , http://en.wikipedia.org/wiki/Interlaced_video




A lot of video standards have been formalized, but they are all have the same mechanism, NTSC which is commonly used in US, has a 29.79 Frames per second, and the number of lines that are scanned per frame 527.  Asia, Europe, 25 FPS, and 625 Lines. SECAM for France and others, 25 FPS and 625.

Those mentioned standards encode the video signal into something called "composite signal".  A Composite holds  luminance information which holds the black/white image,and  synchronization information. Horizontal and Vertical sync signals.  Referring to the previous figure, You can see a complete description of  composite signal and the timing diagram of an NTSC video standard.  Basically, a horizontal line consists of  
1. A Horizontal Synchronization Pulse, that is used to identify that the line has been scanned horizontally and needs to be reset to the next position for the next line, usually it is called HSync, you can find that term mainly used in Video Generators ICs found in TVs. 
2. Back Porch, that creates a dark frame around the image.
3. Front Porch, that produces the right edge of the image.
4. The black and white information (Luminance) which varies in a voltage range 0 to 1V, where 0.3V represents black, and 1.0V is white, between them is the gray intensities. 
From the figure, one line lasts for 63.5us, at first a 4.7uS sync pulse is sent, so that it tells the TV or the monitor that a new line is going to be drawn, and that is by giving a voltage of 0V. A 52.6uS contains the video data. 

This is only for B/W Video Signal, the color information is transmitted separately, modulated on a higher frequency carrier (  Do you remember Frequency Modulation ?,  Read Openheim or  lathi's book).
A Vertical Syn VSync pluse is also sent to tell that a complete frame or an image has been drawn on the screen and the gun needs to be reset again to line number zero . 

**For Fun
 I remember when I first repaired our home TV old National 1980, and it had  just a horizontal white bar on the screen, and this is for sure means that the vertical deflection circuit in the TV has been broken, and the TV can't try to scan the screen vertically. I changed the Vertical Deflection IC and it worked. Kindly note also the same apperance can happen when the Horizontal Deflection circuits get defected, a Vertical white Bar on the screen appears and that is really bad for a TV, because that always mean that HOT( Horizontal Output Transistor ) and the Line Transformer is defected and this is really an expensive transformer and hardly to be replaced.

How can we generate a composite signal ?

Using any microcontroller, you can use any method that  Digital to Analog Converter D/A to generate a composite signal. Things like PWM, R/2R, a dedicated D/A are enough for that purpose.
All you need is analog voltages that varies from 0 to 1V, but with very precious timing, like you have seen before in the timing diagram, you need to achieve delays in microseconds, which is hard to achieve using C Language, as you can barely know the cycle of the instructions and hence it is better to use assembly language for that purpose. 

A Simple R/2R like the one  shown can be used to generate the required voltages. Note that the input impedance of most TVs is 75ohm, by using voltage divider formulas, you can easily  get the three levels that are needed for generating a composite black/white signals. Make a truth table of 2 bits and check the output. 
This is of course a 2Bit B/W signal, Imagine how a Geforce GTX580 256bit and generative a VGA signal which is more complex than NTSC/PAL Signals..






Sunday, September 9, 2012

Introduction to Embedded Software and Video Game Console Design

SA,

In my childhood, I loved to play games on Atari, Sega,..etc, actually I was addicted. Once My Sega has been destroyed and couldn't work anymore, I tried to open it to see what's inside that box that could make those games. I found bunch of resistors, ICs,..etc. How those silicon chips made those games, I'm wondering.  I was also eager to know how those " dead pictures" can become alive.

A video game console is a product that many sciences involve in, from Electronics Engineering who assemble the circuits, to Game Programmers, and Audio Engineers...etc.

I had always the interest to explain to myself how those black boxes work. I will write few blogs in the next few weeks on how to generate a video/audio signals to plot a pixel, then draw lines, triangles, polygons, which can be used to write a small game!.

There are a lot of constraints while using 8/16bit uCs for a console like Sega, that shows the engineers at that age was Amazing, they knew a lot of tricks and optimization, many of them can be found at Michael Abrash's Book on Zen of Graphics Programming. He has also participate on Microsoft's XBox GPU.

Knowing how video game consoles work, will let you know how your GPU also work, writing a software renderer will let you know  how current APIs like DirectX or OpenGL has been written.

I will stick with PIC24 from microchip, it is a fast uC, and in the next blog, I will explain the basic circuitry that is needed for that project.


Sunday, September 5, 2010

حال بنات مصر .. عن تجربه

ميرسي .. هذا رد بنت لا تعرف الفرنسيه اساساً .. العنتظه و الفشخره اهم صفتين في البنات الحاليين حتي لو مش لاقيين ياكلوا .. اي بنت تجدها في سيتي ستار " ملجيء الحريم" تاكل بالشوكه و السكينه و النظره الفخوريه و اللبس المضروب من ازبل المحلات و لكنه خليع و شكله مغري و التي لا ترضي إلا بشاب شيك ، معاه جاجوار معاه فلوس لتعوض النقص اللي عندها من خلاله و لبس غالي يلبسونه المحترمات محبات الماركات المتأمركات من ارقي الطبقات التي لا ترضي إلا و بشخص لابس جزمة من تمبر لاند او سروال داخلي من كويك سيلفر ! لكي فقط تعوض النقص في نفسيتها في ان اصحاب الطبقات الاجتماعيه العليا هم بس فقط من يلبسون من هذا النوع

نأتي إلي المتعفنين فكرياً في الجامعات و منتحلين التدين و بعدهم عن الدنيا و السيئات و الاصرار علي حضور مشايخنا الكبار العلماء مثل مصطفي حسني و عمرو خالد في الخلوات .. يا احمد صليت الفجر انهارده .. ايوه يا حبيبتي .. بحبك يا حبيبتي .. هنخرج فين انهارده ؟ هنروح عند درس مصطفي حسني يوم الاربعاء .. اكيد طبعاً .. انا هاجي و هوصلك..ميرسي يا حبيبي

نأتي إلي محبات البدلات البيضاوات و البنيات ... حتي لو مرتباتهم ضعيفه و حياتهم صعبه و كفيفه لكن ده صاحب مركز اجتماعي في مجتمع مُدمر نفسياً و حاسس بالنقص و فقدان الامان و حب السلطة كبديل .. لا انا هجيلك الشغل و اشوفك بالدبلة بتكون عليك قمر و موز ... ميرسي يا حبيبتي ..

نأتي إلي بنات اولاد اصحاب المقامات ... سائقات البي إم مات .. في الشوارع كالطائرات لابسين نضارات الراي بان .. منتظرة اي مشكلة لكي تكلم دادي العميد او كاتب عند الوزير لكي تُنكل بإي شخص يملس سيارتها الفخمه التي ستصبح عانسه موديل قديم مثلها...

و اخيراُ المكافحات من معدن اصيل تركب الميكروباص بحثا عن لقمة العيش ملتزمه حتي لو آثر المجتمع عليها بالسلب تقرأ القرآن في المترو تذهب للعمل تريد حياة كريمة ...مكافحة شريفه عفيفه ...ربنا يحميكم لينا
احمد

Wednesday, November 11, 2009

Who should Rule Egypt ? من يجب ان يحكم مصر ؟

يجب من يحكم مصر ان يكون دكتور في الهندسة و عالم في التكنولجيا و الالكترونيات و الاتصالات و الكلام ده ، او يكون عالم زي زويل ، لان نهضة الشعوب بالعلم الان و سلاح اي دولة هو العلم الان ، شوفوا الهند و ماليزيا عاملين ازاي ، مش محتاج اتكلم عنهم ، ولازم يكون عارف انه جاي علشان يصحي مصر من الغيبوبة اللي فيها في التعليم و الصحة و المستشفيات التعبانه ويطبق التكنولوجيا فيها و يقوي الصناعه و يستغل الايدي العامله ، و يمحي الفساد ازاي ؟ لان اي رجل عالم في التكنولجيا بيحب العمل و اللي مش هيعمل كويس هيشيله . مينفعش رئيس مصر يكون واحد في الاعلام زي عمرو خالد و بياخد فلوس علشان الكلام ده ، مينفعش هيفيد البلد بايه ؟؟يقدم برامجه علي القنوات المصرية ؟؟ هذا غير مؤهل علميا اطلاقاًًً و كل واحد و ليه مجاله !! مينفعش رئيس مصر يكون اكبر من 55 سنة ، احنا عايزين حد وصل لاعلي الدرجات العلمية في سن صغير وفي منهم كثير . مينفعش نرشح حد من الجيش و يكون كل همه و فكره في زياده مرتبات الظباط و الداخليه وولائه للجيش ،ونسيب التعليم و الصحة يخربوا بقي. هتقولوا عايزين الجيش قوي و بتاع ، اي حد عالم في مجال الصناعة و التكنولجيا هيقدر يزود الجيش باحدث المعدات و ان شاء الله تكون من صناعة بلدنا ولا نحتاج لاي معونات خارجيه .عايزين حد يقفل علي البلد و منشغلش بالنا بالناس اللي حوالينا انتم فاهميني ، حماس و مش عارف ايه ، لازم نركز ان اننا نبقي قوة عظمي و نهتم بحال البلد اكثر . رئيس ايران دكتور مهندس احمد نجاد ، و ايران عملت قمر صناعي و عملت ميكروبروسيسور و عندها مصانع الكترونيات و اتصالات و كل ما تتخيله ، زي ماليزيا ماسكها دكتور .. حاولوا تفهموا بقي !!! عمرنا ما هنتقدم غير لما يمسكنا حد فاهم في الكلام ده ، هيقدر فعلا يوفر لينا تعليم جيد ، و صحة . هتقولوا و الدين و الاخلاق و القيم ؟ قلك كل مشاكلنا تقريباً هي الفقر و الفقر يخلي الناس مش تشتغل و مش تتجوز و ده يخلي الشباب يتحرش ، يتعاطي مخدرات ..إلخ لما نوفر فرص عمل و مصانع ..إلخ هتلاقيهم مسكوا بيت و صانوا انفسهم ، و بطلوا السجاير علشان المصاريف و بدأوا يصلوا ..إلخ عايزين رئيس عالم يقدر يوفر العدالة الاجتماعيه ، مش معقولة شخص معاه عربية مرسيدس 2010 و ياخد بنزين مدعم بنفس سعر البنزين الي بياخده اللي معاه موتوسيكل !!! مش عايزين واسطه ولا محسوبية في التعيينات ، و ياريت بقي كل الناس اللي بقالها اكثر من 50 سنة تقعد معاش و القيادات يبقوا الشباب و هما اللي يمسكوا المناصب و من الشباب اللي واكل فول الصبح ، لانه هو الوحيد اللي بيحس الان لانه هو اللي حاسس بالمعناه و لما يلاقي شاب زيه فقير و كان في نفس وضعه و لا هيتعبر الواسطه و لا المحسوبية .
No need for english translation ,because that topic is written for only Egyptians :).

Wednesday, November 4, 2009

خواطر و حقائق Facts

إن من ابرء و اصدق الصداقات ، هي صداقة الطفولة ، الان احسست بقيمتها ، صداقة لا تعتمد علي المصالح الشخصية و لا اغراض دنياويه ، ليتني اعرف ذلك ، لكنت قتلت الزمن الذي جعلنا نتفارق الان. افتقدكم .. احمد
حب الطفولة من اجمل اللحظات التي يعيشها الانسان ،من منا لم ينس ملامح بنت او ولد كانت تدرس معه في فصله الدراسي ، او بفصله الاخر ، كان الحب هذا هو فقط انك تريد ان تري وجهها ، لم تر الغرائز و الشهوات النور في هذا الوقت ، كل ما تريده هو انك تراها و بكل برائه و خجل تتحدث معها ،فاين انت يا حب الطفولة فينا الان ، لقد اخمدتك الدنيا بملاهيها و لكن كلما طال الزمن ،ستظل الذكريات تُحييك .. لم انساك.. احمد
كلنا زوار في هذه الدنيا ، نقابل ناس و نفارقهم من الطفولة إلي الشيخوخه ، كل شخص قابلناه آثر فيك ايها الانسان ، فهل يتذكر اي انسان كم من الوجوه تعرفت عليها و تحدثت إليها منذ طفولته في المدرسة إلي شيخوخته ؟ هل فقدت اناسي تريد ان تراهم و لا تعرف كيف تصل لهم ؟ هذا هو حال الدنيا ، و كما قال الله عز و جل " و ما الحياة الدنيا إلا متاع الغرور" ، لا تقلق ، سيأتي يوماً نتقابل فيه جميعاً و لكن امام
الله ... احمد

Childhood friendship is the purest friendship ever , Now i feel its value , its a friendship which doesnt depend on Personal interests , nor purposes of secularization, i wish i knew these facts, i would kill the time that made us seperate now, I really missed you .. Ahmed Saleh .

Childhood love , is one of the most beautifull moments that the human live. Im sure no one had forgotton the features face a girl or a guy who was studying was her at the same class or another class . You just want to see her face , The Instincts and desires werent born yet , all you want is just to see her , and with a shy face you wanna talk with her . Where are you Childhood love now, that life killed you by its desires , but whenever the life passes , the memories will make you wake up ... Ahmed Saleh

We are all guests in this world, we meet people and leave them from childhood to old age, everyone we met influenced you, O man, does any human being remember how many faces he met with and talked to them since childhood to old age in school? Have you Lost people and want to see them and do not know how to reach them? This is how bad life is , and as the God Almighty says "and the pleasures of worldly life only vanity," Do not worry, we will meet one day , but under the hands of Allah... Ahmad

Tuesday, October 27, 2009

مرض الشيزوفرنيا !

لا تتعجب من مهندس و هو يتكلم عن الطب ، فاغلب المهندسين يحبون معرفه ما يسمونه بالميكانيزم و معرفه كيف يعمل الجسم ..إلخ من الهرطقات :) .
كثير من الناس في المجتمعات العربية يضحكون علي كلمة شيزوفرنيا و كأنها كلمة تعني انك مجنون رسمياً او انك تعاني من مرض فزيع ! و كما آثار الممثل احمد حلمي في فيلمه اسف علي الازعاج و هو يعاني من هذا المرض و جميع النقاد يقولوا انه اول من اثار هذا الموضوع في السينما المصرية ، و هم لا يعلمون ان فؤاد المهندس في افلامه لا اتذكر اسمها ذكرت الكلمة بين دكتورين اجانب ، يقول واحد للاخر ، شيزوفرنيا ،و الاثنين يختلفوا !
الشيزوفرنيا هو مرض الفصام ، و هو مرض يصيب اي شخص و هو يتوهم بأن هناك شخصيات تتحدث معه و تسمي هذه الاشياء بالضلالات delusion .
النقطه التي ارجحها هو سبب خلل كيميائي في المخ ، حتي ان بعض الادوية توصف عقارات تقلل نسبة الدوبامين في المخ و هذه الادوية تسمي مضادات الذهان Antipsychotic .
و انا اعرف بعض العقارات الناجحه في هذا الامر و الجرعه منها مثل الدوجماتيل 200 قرص يومي ، و عقار البيبريكس و لكنه غالي الثمن ، لا تستغرب كيف اعرف هذه الادوية ؟ لقد قابلت للاسف في حياتي حوالي ثلاث حالات منهم اصدقاء غير قريبين و جيران و هذا ما جعلني ابحث عن المرض و تفاصيله .

النقطة الغريبة في الموضوع هو ان هذه المعلومات تعتبر معلومات هامه ، فالمجتمع الامريكي معظمهم يكونوا عارفين بالمصطلحات الطبية و حتي انواع الامراض ، و لديهم معرفه ليست بكثير ، علي عكس المجتمع العربي ، و المصري بالخصوص ، الذي يفتي كثيراً حتي تجد في العيادات إناس يفتون في مرضهم و هذا ما يجعل الاطباء ضعاف النفوس في استغلالهم ، يجب ان تعرف ما هو مرضك و ما هي الادوية المرجحه له و هذا متوافر علي الانترنت .
Many people just laugh at the word schizophrenia , and they think that your totaly a crazy person when they describe you that ur a schizphornic ! . This sickness has been filmed in a movie called " Asef ala el ez'ag" by ahmed helmy , however the criticizers of the movie said its the first movie in the egyptian cinema which described that sickness , its not true ! . That word has been said in Fouad el mohanes movies , by a Comedy thing . This word is spread in the egyptian community and many people dont know what it really means , and as you know , egyptians like to talk too much and never say the word I DONT KNOW THIS .
Schizophrenia is sickness in the brain , In my humble opinion its a problem in the chemics of the brain , especially the increase in the dopamin , the patient feels or sees some delusions something like that he /she talks with persons that aren't actually there . Medicines are called Antipsychotic are usually described for the treatment of that sickness , which decreases the dopamin in the brain . Something like Dogmatil or Alpiprix which is really an expensive medicine .
The strange point in this topic is that information are really important , and most people in the usa community whatever patients or healty people really know about that sickness or the symptoms , and that's really a good point , unlike here in the egyptian community where patines just take the medicine and they dont know what they actually take or from what they suffer , althought understanding the sickness is the FIRST step to be able to be cured !.

Monday, October 26, 2009

Monday, October 19, 2009

Line Tracking using PID using 89S52

First I'd like to thank So ChikMan From Hong kong HKU, he is a pioneer in control engineering besides, he has repersented his country many times in Robocon contest, he has a great impact on teaching me the theory and operation of PID Control.

Hi, In robocon 2008, i've tried to implement the well-known algorithm in Control engineering the PID ( Proportional -integeral -derivative), I was having a great experience using the microcontroller from ATMEL 89S52 , plus I've already designed a complete board using it at the past years of the contests , and due to low fund, I've used it again. The problem is that uC doesnt have a PWM Hardware module so you've to write your own Software PWM, also it doesnt have an ADC ( anlogue to digital converter), and i've solved this by using a crude way of doing an ADC which is using a compartor like LM324.

The idea is there are 6 sensors (some people uses 8 or 16,or 32! depends on your complexity of design and speed you want to achieve), These sensors will give you the position of the robot from the line which it follows considring that the output from the sensors are Digital , so you've to define some numeric values to enumrate for the posssibilites of the position of the robot on the line to be tracked.

Consider that 1 is the value on white which means your on the line, and 0 is the value when your away from the line. Consider The sensor arrangement as this xxxxxx, let it be L1L2L3R3R2R1
Consider that L3, R3 have been positioned to be on the line , and the other sensors are seprated by 10mm.
The Pid algorithm calculates the error from the feedback element which is our 6 line sensors , when L3,R3 are on the white line, which means the robot is going straight and it also means the the Error is 0, which is our desired value or what's always called in control engineering text books ( Set Point ).
pseudo code :
error = setpoint- measured value .
If you've a control engineering textbook, you will see many figures of the well-known control loop which is familiar to many engineers.
The measured value should be a predfined numeric values because we dont have an ADC here.
We will define it like in the code.

Code List using 89S52

void init_timer0(void)
{
EA=0; // disable gloabl interrupts

TMOD=0x02; // 0000 0010
TH0=0x9B; // Timer values
TL0=0x9B; //
PWM=0;
ET0=1; // Enable timer interrupt 0

EA=1;
}


The Software PWM Code
// Motor1_2 , is the enable pin of the motor for PWM
// pwm_l , r are the values of the PWM which be sent to the motor , from 0 > 11
void timer0(void) interrupt 1 using 0
{
TR0=0;
PWM++;
TL0=0x9B;TF0=0;
if (PWM==11) PWM=0
if (PWM <= pwm_l) Motor1_2=1; else Motor1_2=0; if (PWM <= pwm_r) Motor2_2=1; else Motor2_2=0; TR0=1; }



// Do this in a 20ms (sampling time) control loop

void Line_Track(void)
{
int mpos;
float error,Rate,Deriv,previous_error;
pwm_r_=11;
pwm_l_=11;
TR0=1;
Walk(1); // move forward
if((Sensor_1==0)&&(Sensor_2==0)&&(Sensor_3==0)&&(Sensor_4==0)&&(Sensor_5==0)&&(Sensor_6==0))
{
mpos=0;
}
if ((Sensor_1==1)&&(Sensor_2==1)&&(Sensor_3==1)&&(Sensor_4==1)&&(Sensor_5==1)&&(Sensor_6==1))
{
mpos=0;
}
if ((Sensor_1==0)&&(Sensor_2==0)&&(Sensor_3==1)&&(Sensor_4==0)&&(Sensor_5==0)&&(Sensor_6==0))
{
mpos=-1;
}
if((Sensor_1==0)&&(Sensor_2==0)&&(Sensor_3==0)&&(Sensor_4==1)&&(Sensor_5==0)&&(Sensor_6==0))
{
mpos=1;
}
if((Sensor_1==0)&&(Sensor_2==1)&&(Sensor_3==0)&&(Sensor_4==0)&&(Sensor_5==0)&&(Sensor_6==0))
{
mpos=-2;
}
if((Sensor_1==0)&&(Sensor_2==0)&&(Sensor_3==0)&&(Sensor_4==0)&&(Sensor_5==1)&&(Sensor_6==0))
{
mpos=2;
}
if((Sensor_1==1)&&(Sensor_2==0)&&(Sensor_3==0)&&(Sensor_4==0)&&(Sensor_5==0)&&(Sensor_6==0))
{
mpos=-5;
}
if((Sensor_1==0)&&(Sensor_2==0)&&(Sensor_3==0)&&(Sensor_4==0)&&(Sensor_5==0)&&(Sensor_6==1))
{
mpos=5;
}
if((Sensor_1==0)&&(Sensor_2==1)&&(Sensor_3==1)&&(Sensor_4==0)&&(Sensor_5==0)&&(Sensor_6==0))
{
mpos=-4;
}
if((Sensor_1==0)&&(Sensor_2==0)&&(Sensor_3==0)&&(Sensor_4==1)&&(Sensor_5==1)&&(Sensor_6==0))
{
mpos=-4;
}
if((Sensor_1==0)&&(Sensor_2==0)&&(Sensor_3==0)&&(Sensor_4==1)&&(Sensor_5==1)&&(Sensor_6==1))
{
mpos=3;
}
if((Sensor_1==1)&&(Sensor_2==1)&&(Sensor_3==1)&&(Sensor_4==0)&&(Sensor_5==0)&&(Sensor_6==0))
{
mpos=-3;
}
// PID Equations

error=-mpos; // error = 0 - feedback , 0 is the center
error=error*2.2; // KP*ERROR , Kp=2.2
Rate = error-previous_error;
Deriv = Rate * 2.0; // KD = 2.0
previous_error=error;
error=error+Deriv; // PD Terms

// CUT Terms
// error is negative , robot is going to right
if (error < pwm_r =" plus"> 0){
pwm_r_+= ABS(error);
pwm_l_-=ABS(error);
}
if(pwm_r_>11)pwm_r_=11;
if(pwm_l_>11)pwm_l_=11;


}


Videos

Fast line follower
http://www.youtube.com/watch?v=g2_9nDmEmPo

Doing a task
http://www.youtube.com/watch?v=kiqopmLjFjE



Eng.Ahmed Saleh Mohammed
El Shorouk Acadmey
Electronics and communications engineering department

My Quotes

Ahmed Saleh's Quotes
Written by Ahmed Saleh

1. Electronics Engineering + Computer Science + Mathematics == A Computer scientist
2. Both Gates and Einestien created an evoultion In software and physics, Although they had belived trinity ..etc .
3. Love is a Power measured in the number of pulses of your heart when you see her eyes,its unit is Watt

4. Engineering is the science which i love, but my love to you is another science which adore - Ahmed Saleh

5.My love to you is like blood flowing in my body, if its ended  ÷would die . - Ahmed Saleh

6. If u wanna "Feel" the real love, then "Watch" two blind couples - Ahmed Saleh

7. Physics concern with how things work, chemistery concerns with how things are constructed, mathematics concern with why things actually work. - Ahmed Saleh

8.If you wanna be a very talent designed engineer, Don't put your hands in your poket and design from used materials.

The Start

This blog is mainly about Electronics engineering, and Software Engineering, Also it reflects few viewpoints in my life.