You are currently browsing the category archive for the ‘électrique’ category.

De temps en temps, la technologie du transistor devient important car elle décide quelle ère est on.

En principe, un transistor représente un interrupteur dans le circuit qui permet de faire passer le courant ou pas selon l’entrée de la base, le contact au milieu.

Par exemple:

Pour PMOS, si l’on alimente la base (on appelle aussi la grille G), le transistor devient un interrupteur ouvert. Si elle n’est pas alimentée, le courant traverse le transistor.

Pour CMOS, c’est l’inverse, voir le figure.

Selon la technologie du transistor, on a des catégories différentes:

Silicium pour les débutants.

lien: http://www.rfdesignline.com/showArticle.jhtml?articleID=209100059&cid=NL_rfdl

Choosing the right package for your design yields tangible benefits

Courtesy of EE Times

When creating a new integrated circuit, the initial focus is naturally on the design. When it comes to tapeout, then fabrication, multiproject wafer (MPW) services are growing in popularity as deep-submicron technologies become the norm and as both mask and wafer fabrication costs soar. However, device packaging is often overlooked until the end of the process. That may be because some fabs and MPW providers have relatively little to offer with respect to packaging, or it may be simply that designers see packaging as the last thing they need to worry about.

In fact, choosing the right package both during the creation of a chip for the test phase of development and for the final device can not only reduce your time-to-market, but also help you create tangible benefits for your customers.

The choice of packages has never been greater, and some MPW providers now recognize the importance of providing chip developers with optimized packages throughout the development of silicon devices. Most frequently, this is done through partnering with established packaging specialists. Let’s take a look at some of the available options and what they have to offer.

System-in-package combines IC, discrete and passive parts within a single custom or standard-outline SIP

Open-cavity packages

Open-cavity packages are ideal for focused-ion-beam (FIB) analysis and for probing silicon devices during development. Being able to carry out such tests directly on the die is an important factor in speeding design work and ensuring device integrity before moving to volume production. Until relatively recently, however, such packages were usually large ceramic types. These are expensive, and high-speed signal integrity cannot be evaluated accurately, because package interconnects are not the same as those in the final package.

Recent developments have changed all that, and open-cavity packages are now available in several popular formats, including QFN/MLP, QFP and SOIC/SSP. These premolded packages meet the latest Jedec outline and footprint standards. Their copper lead frames are gold-plated to military standards, so they are mechanically stable and have electrical characteristics very similar to fully encapsulated, molded types that would be used in volume production. Typical package sizes range from 3 x 3 mm to 10 x 10 mm.

Chip-scale packages

Chip-scale packaging (CSP) is increasingly popular because of its relatively low cost, small size and high performance. It provides protection for the die surface, minimizes stress between the printed-circuit board and the die, and facilitates changes in interconnect arrangements between the die and pc board. High-speed signal performance is particularly good because interconnects are kept very short. Rather than the conventional process of wafer fabrication, dicing and packaging, the creation of wafer-level chip-scale packages involves packaging complete wafers and then dicing them.

Creating a CSP involves covering the wafer with a layer of passivation (polyimide), then etching vias down to the bond pads–traditionally located around the outside of each device–and filling the vias with conductive material. A copper retracing layer is then deposited, connecting to the top of the vias and forming a matrix pattern across the whole chip. Solder bumping–creating the balls that will contact the board–is achieved by depositing a thick layer of passivation, etching vias into this at the desired connection points, then filling the vias with solder. The top layer of passivation is then removed, and surface tension makes the columns of solder form into ball shapes.

Highest performance is achieved by keeping critical signals on the outside of the device so they have the shortest connections to the die. CSP also offers good thermal performance; heat is easily dissipated because there is no insulating packaging surrounding the die.

Stacked-die method

Where space in the X-Y plane is at a premium, stacked-die packaging allows for very efficient use of motherboard real estate, reducing size, weight and system cost. Taking the MPW route with stacked-die packaging can allow complex systems to be prototyped earlier than waiting for a single IC to be developed. Using stacked dice can therefore be a good way to prove that a design meets the required specification, on the way to moving everything onto a single process. For example, flash memory, digital and analog elements of a design can be produced on different dice but housed in the same package.

The technology also enables the flexibility of combining custom chips with off-the-shelf devices to reduce system cost. Dice are tested before being put into the stacks to ensure that only known-good dice (KGD) are used.

Three approaches can be taken to stacked-die construction: same-die stacks, pyramid stacks and overhand cross stacks.

When two dice are used, the maximum package height will typically be in the region of 1.4 mm. It is also possible to stack three or more dice in a single package when board space is limited but a little more height is available.

The most common applications for stacked-die packages are in portable electronic devices such as cell phones, PDAs and other wireless consumer systems.

System-in-package

The system-in-package (SIP) approach is becoming increasingly popular not only for its very high density but because as passive component sizes shrink, the devices become more difficult and expensive to handle. Ceramic capacitors that measure 1 x 0.5 mm are now common, and devices down to 0.4 x 0.2 mm are available in values up to 1000 pF at 6.3 Vdc.

However, the cost of capital equipment to handle such tiny parts can make it difficult to find an economical way to take advantage of the available miniaturization.

The SIP approach combines multiple ICs, discrete semiconductors and passive components onto a single package, providing a complete functional system in one module that can be processed much like a standard component during board assembly. Unlike system-on-chip (SoC) designs, which employ a singe die, SIP designs are integrated by stacking or placing chips and components on a substrate, typically a BGA laminate or QFP lead frame.

SIP has performance and size advantages over component-level designs. In digital circuits, it can provide better memory bandwidth than SoC-based designs. And in analog and mixed-signal designs, the proximity of passive and active parts minimizes stray capacitance and unwanted inductance to optimize high-speed signal performance.

About the author

Wes Hansford (hansford@ mosis.com) is deputy director of Mosis. He has 25 years’ experience working in the semiconductor industry in technical and management roles. He holds an MSEE degree from the University of Southern California.

lien : http://www.eee-pc.fr/2007/12/14/eee-pc-le-bluetooth-a-portee-de-fer-a-souder/

L’info vient de 01Mobile dont l’un des membres à posté une série de photos d’un démontage en règle de l’EEE PC (largement plus que le nécessaire pour faire sauter la garantie Asus) pour y intégrer un module Bluetooth interne.

Le principe est simple, et est applicable sur n’importe quel modèle d’EEE y compris le 8G qui n’avait pas de place libre à cause de la carte Mini PCIe : il s’agit “simplement” de placer le module USB Bluetooth à l’intérieur de la coque de l’écran, qui dispose d’un espace largement suffisant comme le montre la photo suivante.

bt04.jpg

Pour le côté technique il s’agit de placer un Hub USB à la place de la connexion USB de la Webcam pour que celle-ci continue à servir et pour pouvoir brancher nos périphériques USB, soit la clé USB Bluetooth dans ce cas là.

Un joyeux bricolage !

bt01.jpgbt02.jpgbt03.jpgbt04.jpgbt05.jpgbt06.jpgbt07.jpgbt08.jpgbt10.jpgbt11.jpgbt12.jpgbt13.jpgbt14.jpgbt09.jpg

Et ca marche ?

Après avoir tout branché, l’auteur du mod relance windows avant de refermer la coque pour vérifier que tout marche bien, y compris la webcam. Et il le confirme bien, la webcam continue à filmer sans problème.

bt15.jpg bt16.jpg

On referme tout et voilà un EEE PC qui reconnaît la clé bluetooth sans problème, bien que vous aurez du mal à reconnaître le texte !

bt17.jpg

La majorité se contenera cependant d’utiliser une mini clé USB Bluetooth pour ses besoins, surtout avec les mini dongles qui sont quasiment invisibles une fois insérés dans le port USB. Mais pour les accrocs de la bidouille et les roi de l’électronique, c’est un avantage indéniable d’avoir le Bluetooth en interne et cela laisse présager des mods intéressants pour la version 4G en utilisant l’espace interne du slot Mini PCIe en plus de celui de l’écran pour faire un mix de bluetooth, gps, mémoire, …) même si je commence à douter de l’utilité d’un EEE dans ce cas là, si les différents mods doublent son prix, pourquoi ne pas prendre directement un ultra portable plus performant ?

lien : http://www.eee-pc.fr/2008/03/04/installer-gps-eeepc/

p1000342.jpg

Perdu dans les rues ? Impossible de trouver le village de vos vacances ? Et bien votre EeePC pourrait vous aider en se transformant en GPS pour vous montrer la voie !

Tout d’abord un petit avertissement, la solution est loin d’être aussi économique qu’on pourrait le croire. Il faudra compter environ 50€ pour le module GPS, une 30aine d’euros pour une carte d’Europe complète, éventuellement un chargeur sur allume-cigare et bien sûr un EeePC, alors que l’on peut trouver des GPS autonomes à partir de 100€. Pour le côté pratique, j’attendrais le test en utilisation réelle pour me prononcer, cet article est plus un avant-goût de ce que l’on peut en espérer. Il faudra donc attendre la suite de cette série d’article pour avoir un tutoriel complet pour transformer votre Eee en GPS ;)

Quel module GPS choisir ?

J’ai choisi un module USB, le Holux GR-213, à la suite de certains avis. Je ne suis pas encore sûr que ce soit le meilleur choix, lui ayant déjà trouvé quelques défauts, mais ça sera l’objet du prochain article de cette série.

Pre-Installation du GPS sur l’EeePC

Si ça n’a pas déjà été fait, il va falloir mettre à jour les dépôts de votre Eee pour avoir accès au serveur contenant les librairies et logiciels (basique) de GPS. Cela vous permettra aussi d’avoir accès à beaucoup plus de choix pour des programmes via apt-get ou synaptic.

Ouvrez une console (Control + Alt + T) et recopiez cette commande :

sudo nano /etc/apt/sources.list

Ajoutez ces lignes à la fin du fichier, sauvegardez et quittez

deb http://xnv4.xandros.com/xs2.0/upkg-srv2 etch main contrib non-free
deb http://dccamirror.xandros.com/dccri/ dccri-3.0 main
deb http://www.geekconnection.org/ xandros4 main
deb http://download.tuxfamily.org/eeepcrepos/ p701 main etch

Installation du GPS sur l’EeePC

Tapez les commandes suivantes pour mettre à jour la liste des paquets disponibles et installer les programmes qui nous intéressent.

sudo apt-get update
sudo apt-get install gpsd gpsdrive

Il ne reste plus qu’à lancer gpsd (il est censé se lancer automatiquement lors du branchement du GPS mais il semble y avoir quelques soucis à ce niveau là) puis l’application graphique gpsdrive.

gpsd /dev/ttyUSB0
gpsdrive

Premières impressions

p1000341.jpgLe module GPS met assez longtemps (par rapport à mon GPS autonome) à se synchroniser je trouve, je ne sais pas si cela vient du modèle Holux, de la gestion du GPS par Linux où bien du logiciel GpsDrive utilisé pour ce premier test. Mais le début du trajet est en général le moins important, on sait toujours plus ou moins dans quelle direction aller le temps que le GPS se synchronise.
Et le plus important est que cela m’affiche bien mes coordonnées GPS, qui correspondent bien à l’endroit où je me trouve. La mesure de la distance restante est en accord avec celle réellement parcourue, cela confirme que l’EeePC actualise sa position sans soucis.

p1000343.jpgp1000345.jpg

La mesure de la vitesse est aussi intéressante, à supposer qu’elle puisse être exploitée correctement par un soft de navigation : estimation du temps restant, alerte sonore lorsqu’une certaine vitesse est dépassée, etc … Il y a un temps de latence au moment de l’accélération, mais une fois que la vitesse devient stable, la mesure est plutôt précise (les 2 photos au-dessus ont été prises à quelques secondes d’intervalle) et donc, en théorie, exploitable.

La prochaine étape ?

Tout d’abord, il faudra que je trouve un moyen de fixer l’Eee dans la voiture de façon simple et économique. Si vous avez fait ça, vos suggestions m’intéressent )

Et bien sûr, installer un logiciel de navigation. Pour Linux le plus complet semble être NavIt, qui semble accepter un large choix de cartes tout en proposant des fonctionnalités proches des logiciels commerciaux. Et bien sûr tester le tout lors d’un trajet pouvant réellement bénéficier de l’assistance du GPS, avec à la fois l’EeePC et un GPS autonome, afin de pouvoir mieux déterminer les avantages et inconvénients cette utilisation.

La suite au prochain épisode article… Ou sur le forum en attendant !

lien : http://www.popsci.com/diy/article/2008-05/eee-pc-school-add-keyboard-backlight-under-15

As we showed you in our May 2008 issue, Asus’s Eee PC has quickly become a favorite of hardware hackers around the web. Here, we offer the first installment of our Eee PC School series. Check back in the coming weeks for more tiny ultraportable tweaking.—Eds.

What good is that portable PC if you can’t type anywhere and anytime? With its ultra-compact keyboard, even touch typing pros will be hard-pressed to avoid frequent mistakes on when the lights go out. To say it’s a frustrating exercise in futility to locate the miniature F3 key in the dark is an understatement. Oops, you just lost WiFi contact by accidentally hitting F2.

Clearly, a keyboard backlight like those found in higher-end laptops is the answer to your nocturnal Eee PC typing woes. And for less than $15, such a backlight can be installed with minimal fuss.

Time: 3 Hours
Cost: $13.50
Difficulty: Moderate

Parts

Steps:

Open ‘er Up.
Before beginning, remove the battery from both the Eee PC and the Techno Flash EL Wire device, and be sure to touch a grounded metal object to discharge any static electricity. Release the keyboard from the PC’s case base. There are three small dents along the upper edge of the keyboard that must be depressed for tilting the keyboard up and away from the case. Detach the keyboard from the main PCB and locate and remove all of the screws from the upper and lower case halves. Separate the case halves and leave the PCB seated in the lower case half.

If you need more visual guidance for opening the Eee PC, see this tutorial.

WARNING: While Asus has been somewhat non-committal on the warranty status of hacked Eee PCs, adding this keyboard backlight could very possibly void your warranty, so proceed at your own risk.

EeePC Backlight: Installing: Photo by Dave Prochnow

Snip and Tuck.
You will be attaching the EL Backlight to the metal keyboard tray in the PC’s upper case. Test fit the EL Backlight on this tray. If the backlight is too wide, carefully trim the clear plastic from its two longer sides. When you are satisfied with the backlight’s fit, carefully bend its two solder tabs up, perpendicular to the metal tray and fasten the EL Backlight to the metal tray with a small piece of double-sided tape.

EL Wire, I Presume?
Snip off the EL wire from the Techno Flash. This will leave an approximately 18-inch length of black cable attached to the IM-4 EL inverter power source. Carefully remove one-half inch of the black cable and reveal a black and red wire. Strip and tin the ends of these two wires.

EeePC Backlight: Wiring: Photo by Dave Prochnow

Take the Low Road.
Snake the red and black wires (along with the black cable) inside the Eee PC via the security lock slot in the right-hand side of the lower case. If the black cable is too large for safely slipping through this slot, carefully strip away more of its length without damaging the black and red wires that are encased inside the cable. Route the black and red wire ends through a small circular hole on the right side of the metal tray and solder the wires to the two EL Backlight solder tabs. Ideally, these two wires should not rest on top of the metal tray.

Polarity doesn’t seem to matter with these solder tabs. Therefore, solder the red wire to one tab and the black wire to another tab. Insulate all wires and solder tabs from any contact with the keyboard’s metal tray. Test your wiring. Add two batteries to the Techno Flash and turn on the inverter’s switch. The EL Backlight should glow a nice bright white/blue/green color. Remove the batteries and carefully close the Eee PC, fasten all screws, and connect and reseat the keyboard. Don’t force the keyboard back into place. Make sure that your wiring, solder tabs, and insulation aren’t interfering with the keyboard’s proper seating.

Sticky Situation.
There was a lot of hand-wringing over how to fasten the Techno Flash to the exterior of the Eee PC without greatly compromising its portability. While this is a personal design issue, we settled on using good ‘ol Velcro, attached to the outside of the LCD. Remove the belt clip from the bottom of the Techno Flash. Attach a strip of Velcro hooks to the underside of the Techno Flash. Find a suitable site on the outside of the LCD cover and attach a strip of Velcro loops. Choose this site wisely—this is where the Techno Flash will be permanently mounted on your PC.

EeePC Backlight: Mounted : Use Velcro for attaching the Techno Flash to the outside of the Eee PC LCD cover. Photo by Dave Prochnow

Glow Little Glow Wire, Glimmer, Glimmer.
Install batteries in the Techno Flash, insert the Eee PC battery, turn on the PC, and turn out the lights. Ugh, can’t see a thing! Now flick the switch on the Techno Flash. Ahh, now you’re typing in the dark, and constant mistakes area a thing of the past.

Note: Stay tuned to popsci.com/category/tags/eeepc for more Eee PC School hacking in the coming weeks. Extra credit for readers who swap the Techno Flash’s batteries with a LiPo battery system that can be recharged via an Eee PC’s USB port!

lien : http://www.eee-pc.fr/2008/03/17/ecran-tactile-eeepc-2/

Ecran Tactile

Encore une fois, on trouve des choses intéressantes pour l’EeePC sur eBay et cette fois c’est pas douteux comme les batteries 10400 mAh. Pour aujourd’hui, c’est la boutique de fido-dido999, un vendeur spécialisé dans les accessoires d’EeePC et qui a acquis une bonne réputation sur eeeuser.com, qui nous intéresse avec ses kits d’écrans tactiles.

Il faut tout d’abord savoir que toutes les options présentées dans ce billet empêchent l’utilisation de la webcam, afin de pouvoir réaliser le mod sans soudure. Si vous tenez à pouvoir continuer à l’utiliser, alors ce mod n’est pas fait pour vous. Si la visioconférence ne vous intéresse pas plus que ça, voilà donc ce que vous pourrez obtenir en échange (attention, on est très loin d’une vidéo de promo d’un iPhone ou iPod Touch !)

La première option est d’acheter un EeePC déjà modifié. Il s’agit de modèle 4G Surf avec 512 Mo de RAM. La webcam étant de toute façon désactivée avec le mod, la seule différence avec le 4G classique est la batterie 4400 mAh au lieu de 5200 mAh et la possibilité d’avoir la coque en couleur. Plutôt intéressant pour 325€ port compris, à part le fait que l’on obtient un modèle avec un clavier chinois/anglais et sans garantie autre que celle du vendeur.

La seconde option est donc d‘acheter l’écran tactile à monter soi-même, pour un petit peu plus de 50€, frais de port compris.

installer-ecran-tactile.jpg

Les photos fournies sont plutôt claires sur la marche à suivre. Le pack contient l’écran tactile lui même, à placer au dessus de l’écran de l’EeePC (après l’avoir bien nettoyé), et le contrôleur USB qui se branchera à l’écran tactile ainsi que sur la carte mère, à la place de la webcam.

En ce qui concerne le vendeur, fido-dido999, il a une bonne réputation auprès de la communauté de Eeeuser.com. A noter qu’un vendeur concurrent propose pour quelques euros de moins un modèle similaire d’écran tactile en kit, qui semble d’une qualité légèrement supérieure mais à priori incompatible avec Xandros.

Enfin, est-ce que c’est intéressant ? Ça dépend à quel point vous avez besoin d’un écran tactile. Et aussi, il ne faut pas oublier qu’en ouvrant votre EeePC pour rajouter l’écran tactile, vous perdrez la possibilité de faire fonctionner la garantie de la machine. Pour le moment j’hésite encore : la garantie me procure plus d’avantage que l’écran tactile ne pourrait. Mais ça devrait changer une fois que j’aurais configuré mon Eee comme système de navigation, où si Ubuntu Mobile apporte de nouvelles fonctionnalités intéressantes à utiliser avec un écran tactile.

Et vous, vous en feriez quoi d’un écran tactile sur votre EeePC ?

++++++++++++++++++++++++++++++++++++++++++++

easy-mod-eeepc.jpgDans l’article précédent, je vous parlais d’un moyen d’installer un écran tactile sur l’EeePC sans avoir besoin d’être un pro du bricolage avec un kit “sans soudure” vendu sur ebay. En continuant mes recherches, j’ai trouvé des solutions pour réaliser la plupart des mods proposés pour l’EeePC (Bluetooth, Clé USB/Carte SDHC interne, …) sans soudure.

Ce kit est un hub USB préparé pour son intégration à l’intérieur de l’EeePC. Il se branche sur le port USB de la webcam (tout comme le kit pour écran tactile seul) et permet les choses suivantes : garder la webcam branchée, connecter un écran tactile, avoir un lecteur microSD interne easy-mod-2.jpg(choix plutôt douteux de la part du vendeur) ainsi qu’un port USB interne pour y brancher un périphérique de son choix : dongle bluetooth, clé USB, …

Ce kit est vendu environ 35€ sur les enchères Yahoo et le vendeur indique préférer les ventes uniquement dans son pays (Taïwan). Mais le vendeur d’écrans tactiles sur eBay, fido-dido999, a déjà vendu ce genre de kit et a indiqué qu’il en revendrait prochainement, avec, je l’espère, un port USB à la place du lecteur de cartes microSD ! Sinon, avis aux bricoleurs qui voudraient se lancer, il y a sûrement beaucoup de clients potentiels pour ce genre de kit ;)

Enfin un problème pourrait venir de l’intensité maximale de 500 mA fournie par le port USB. Dans un ancien post, j’indiquais les mesures de la consommation de l’EeePC. Pour un mod classique avec Bluetooth (50 mA), Clé USB (40 mA), Webcam et écran tactile (100 mA au maximum d’après la documentation) cela laisse une marge considérable pour la webcam (je n’ai pas trouvé d’information précise sur sa consommation, mais elle est certainement largement inférieure à 300 mA, une webcam USB classique a besoin de 50-100 mA pour fonctionner)

(MAJ) Un modèle similaire de hub USB est disponible sur eBay pour environ 33€ (frais de ports compris). C’est un peu cher pour ce que c’est, mais pas tellement si on réfléchit au temps passé à récupérer les pièces, à y assembler et y tester (après tout c’est destinés à ceux qui veulent réaliser un mod sans avoir à sortir le fer à souder ou à passer des heures à bricoler)

lien : http://www.embedded.com/design/opensource/207603384?_requestid=166949

Embedded.com

Object oriented programming in embedded systems is still not widely employed. Many programmers in this area either come from a hardware electronics background or are pure computer scientists.This article discusses one role that object oriented programming can play in embedded systems while maintaining requirements concerning safety and reliability that are often imposed by standards like MISRA.

I will show how good object-oriented design of embedded software can result in many benefits – smaller code and improved ease of source-code maintenance – but with only a slight trade off in terms of performance.

Using an example as the starting point (a standard timer module written in C that services timer units that are provided by nearly every MCU) I will describe a six step process by which to convert C code into object oriented C++ code classes.

Several steps in this process will illustrate a safe path for migrating this source code into an object oriented class. An instance of this class then is a HW- Timer-Peripheral with a much nicer SW-Interface than registers and interrupts. Then it is a matter of simply instantiating the timer class once per HW-Timer available on the particular MCU.

This process can be applied to any situation where more than a single instance of one type of HW-peripheral is to be used in an embedded project. Measurements of performance and code size are provided and topics like OO-in embedded systems and the improved SW-Architecture will be discussed more generally.

The examples we will work through use two timers on an ARM7. They can be completely worked through without any real hardware, using Keil’s ARM7 simulator and the Keil Realview Compiler only. Because many other MCUs have at least 2 on-chip-timers these examples can be ported to other platforms, too.

Starting point: the standard Timer-Module in C
A hardware-timer is a counter/comparator with reset- and interrupt-logic. This timer « wakes up » an interrupt service routine at regular programmed intervals. But many embedded applications need more timers than HW-timers that are available on a given MCU.

We can duplicate the timer, by e.g. letting the HW-timer interrupt at 1 ms intervals. The ISR can then call function A every 3 ms and call another function B every 5 ms. This way we have used one HW-timer to realize several SW-timers, each with it’s own time base. This method is fairly common practice.

For reasons out of the scope of this article the project’s various timer-functions are registered with the timer-module and will then be called back when their time has come. The timer module (Figure 1 below) is based on a single HW-timer and each registered timer-callback-function has its own time interval. This is very similar to how a cyclic-task-scheduler works.

 

Figure 1. Module and process-flow overview. Registration of timer callbacks (1 & 2) and their cyclic execution (x, a and b)

The time base of the timer module depends on the cycle-times requested by the various application modules. If app. A wants 30 ms and B wants 50 ms, then the HW-timer can realize this using an overall time base of 10 ms. If A wants 9 and B wants 3 ms, then the main time base needs to interrupt every 3 ms.

Raising the interrupt no more often than absolutely necessary saves processor performance. This main-time-base is automatically adjusted (by reprogramming the counter register) when timer-callbacks are registered by means of a « greatest common divider » function.

 

Listing 1

Listing 1 above and Listing 2 below show excerpts of the interface and implementation which realize this concept of a timer module.

The result is a module that represents a single HW-timer and provides many SW-timers.

Let us now return to the main topic and start converting it into a class. Afterwards we will be able the instantiate a class for each HW-timer, where each provides many SW-timers.

 

Listing 2. Implementation of timer module

 

Step #1: Use the C++ compiler
Very often in SW-development it is a good idea to take small steps. This eases tracking down the mistakes later on. So let’s simply try to switch to another compiler. In the Keil IDE we do this by simply renaming the files from *.c to *.cpp. When we change timer.c to timer.cpp and compile it we will see the stricter type checking of the CPP compiler, which we resolve by doing type casts.

if ((g_pOnTimer[timerIdx] != NULL))
becomes
if ((g_pOnTimer[timerIdx] != (TimerCallbackPtr)NULL))

But on rebuilding the changed project a few more linker errors do appear, too:

.\Simulator\Test.axf: Error: L6218E: Undefined symbol TimerCreate (referred from hello.o).

hello.o refers to TimerCreate but timer.o exports _Z11TimerCreatejPFvvE. The CPP-compiler allows function overloading (same function name with different parameter lists). So it has to be able to distinguish between functions that bear the same name. It does it by using name-decoration.

I guess that « _Z11 » means something like CPP function that returns an int and « jPFvvE » represents the parameter list. Unfortunately every CPP compiler I have seen does this name-decoration in a different way. So while calling into a library created by another compiler was possible using pure C this is very rarely so using CPP.

Anyway, this name-decoration explains why a C-module cannot call CPP functions. (Calling C functions from CPP-modules is possible though.) While a C-module expects to find a simple function « CreateTimer » as declared the function provided has a decorated name.

This explains why the files will compile all right but linking fails. Hence, any module that calls functions with decorated names must also be a CPP-Module. In this example we’re forced to convert main.c to main.cpp.

Step #2: Create a simple class  » classes, code-reuse, object allocation
During this and the following steps I will work with a mixture of object-oriented and plain C-code. This will work as long as I ensure that I have only a single instance of the object. The reason for this is  » again  » that I want to proceed in small steps.

Object orientation is analogous to the relationship between a cake and its recipe. I can bake many cakes but I use the same recipe for them all. The recipe is an analogy for code and I need it only once and can instantiate it many times. The ingredients and state of each cake that I bake are the properties of each instance of a cake-object. These are the variables that describe the state of each instance of the class.

One of the advantages of OO is code reuse. We have only one chunk of code for all objects that there are. The distinct objects differ by their individual state. So each object has its own data, but they all share the same code.

From this follows that in every function the code has to know which object it is working on. If you bake 5 cakes in parallel you should know which one to add butter to. When programming this « which one » is the hidden (this) pointer to the object to work on, that gets passed into every function of a class.

In order to understand object-oriented programming it helps to ask: How could I do OO in C? First, I would create a data structure that contains all variables of the module. I would declare a variable of that structure and delete former global variables. Then I equip all functions with an additional first parameter  » the pointer to this new variable.

Finally I would change all these functions to access their data via the new « this » pointer. (This is  » by the way  » exactly how an early version of Keil’s OO compiler worked. It even generated intermediate C-files one could inspect.)

So we need object data. Just as ordinary variables can be declared at compile-time or allocated dynamically, there are both options for class objects, too. This is important because in many embedded systems dynamic data allocation is not allowed or only in certain limits, violates programming guidelines etc.

The reason is that safety critical systems that have to execute for long periods cannot afford memory leaks or fragmentation. However, if such rules apply, simply use static object instantiation as done in this example.

 

Listing 3. Initial class interface

Let’s start by turning the timer into a class. As mentioned above, during the intermediate steps of the C-to C++ migration part of the implementation will be OO, while the rest remains « ordinary C ». We can do that because the OO implementation can still access global variables. I start by creating a constructor and converting the « Init » function. Listing 3 above shows the new class-interface.

Lets declare a single instance of the class (global var in main.cpp):

Timer myTimer = Timer(0);

This declares the object myTimer and will cause the constructor Timer::Timer() to be called. But when? Somewhere in the startup code i.e. before the first line of your own code is being executed! This means that we cannot control exactly when the constructor of a statically allocated class-object is being called.

If it is important to adhere to an initialization order during system-init (e.g. reset hardware, then init) you need to split the initialization into two parts and provide an extra Init() function (see Listing 4 below.)

 

Listing 4. Constructor and init function

The initialization of the former TimerInit() function will now have to be separated. The time independent initialization goes into the constructor. The HW-Initialization is realized within the Init() function of the new class, which I call at the right moment.

Step #3 : Convert all Functions to class methods (except ISRs)
As shown in Listing 5 below, all old forward declarations become protected member functions.

Just move them into the private section of the header file. All so far published functions become public members. In the implementation just prefix all these functions with Timer.This step is quite simple.

So far we have a class with methods but no data. All class methods use global data.

 

Listing 5. Additional methods.

Step #4: Turn the ISR into a class member
Interrupt-Service-Functions differ from ordinary functions in that they are being called by the hardware which simply jumps to the address saved in the interrupt vector table.

Of course, the hardware does not supply a « this » pointer. So an Interrupt-Vector is a pointer to the ISR and a unique resource. This is why the class function has to be static (« static function in OO » means « a function that doesn’t have a this pointer »).

But how does the function know which object it should refer to? (Congratulations if you were just asking this yourself!) Well, it doesn’t, and I’ll start worrying about this when it comes to having more than one instance of the timer. Let’s just get on for now.

1. Remove the forward declaration in timer.cpp
void TimerTx_ISR (void) __irq;
and declarestatic void Tx_ISR (void) __irq;
in the protected section of the class declaration in the header instead.

2. Change the function name in the .cpp file accordingly
void Timer::Tx_ISR (void) __irq

3. Then adjust the interrupt vector to point to the new function
SET_VIC_VECT_ADDR(TIMER_ILVL, Tx_ISR)

Step #5: Global variables become protected member variables
All right. Do what it says and see what happens. Cut and paste the global vars from timer.cpp to the protected section of class Timer. Try to compile: All works fine. It is just the ISR that complains:

« nonstatic reference must be relative to a specific object« .

I admit, this « let’s worry later » of Step 4 didn’t last long here. This is because the ISR uses member-variables now (instead of global vars). Consequently it wants a this-pointer and cannot be static. So, here I want the ISR both to be non-static (so it knows the object’s state) and static (so it can be an ISR) at the same time.

 

Listing 6. Static and non-static ISR

Really I need two functions:

1. The static real ISR. It has to somehow know the object instance and call.
2. the non-static member ISR-Handler function.

This means that I have to save the object instance pointer globally somewhere so that the ISR can refer to it. The best place to do this saving is the constructor. The additional changes required are listed in Listing 6 above and Listing 7 below.

In this step I also changed the variable prefixes g_ (for global var) to m_ (for member var).

 

Listing 7. Store object pointer globally and call « class ISR »

Step #6: Dealing with Multiple Object Instances
If we were using ordinary classes we would be ready now. But here each instance of the timer class represents a physical HW-timer-peripheral. Each HW-Timer has its own interrupt and register set to control it.

 

Listing 8. Header additions for multiple objects

So that each object instance knows which registers to address, I added pointers to the registers which the class now uses instead of the fixed special-function-registers.

These pointers need to be set up in the constructor, depending on which HW-timer is being used. The interrupt specific information (priority, interrupt-channel) is used and set in the same code section. This is shown in Listing 8 above and Listing 9 below.

Just as I saved the object pointer globally (to be used in static ISR) we now need to do this for each instance and add the static ISRs for all HW-Timers, that are to be supported.

 

Listing 9. Initialize correct HW, pointers to SFRs, second ISR

Finally we create a second instance of the timer (in main.c) and use the second timer. The test shows how well these two timers work.

Compare and contrast
Now it’s the time to compare the initial and final projects with respect to performance code size. For performance measurements I decided to measure the time spent in the ISR (including calling the callbacks). This is the time that reflects the amount of processor time used by the implementations. These results are shown in Table 1 below.

The differences in terms of SW-Design, ease of source code maintenance can only be discussed qualitatively and individual preferences will lead to different results. Personally, I prefer the OO solution when I have more than one instance because I have only « one instance » of source code and do not need to worry about keeping it in sync.

 

Table 1. Comparison of code size and performance.

These results are not surprising. The OO-solution needs an additional this-pointer. Dereferencing member variables and passing the additional parameter takes a little more time and consumes RAM. The code size is also a little more but advantageous for the second instance.

How useful are objects for real applications? Of course, the use of two instances representing two HW-timers is not so obvious. But think of applying this model to other applications. How about several independent stepper-motor-drives that run entirely in HW. They run synchronously due to the common oscillator clock.

I can also imagine applications where it would be very useful to have instances of a class that represent a group of identical or very similar peripherals. Think of Bus-Couplers. Here you may have some Bus-HW, that receives data on one end and copies (possibly after filtering) it to another Bus-HW of the same kind (maybe at another bus speed). Many MCUs have several identical communication peripherals on board that could well be implemented in this way.

Dirk Braun graduated from King’s College, University of London. His background ranges from software design and development to the electronics of embedded systems. He has recently developed a data centric RTOS and can be contacted at dbraun@cleversoftware.de.

Blog Stats

  • 241,460 hits

Archives

RSS Flux inconnu

  • Une erreur est survenue ; le flux est probablement indisponible. Veuillez réessayer plus tard.