Obscure Soundchip Tuesday: The SGS M114

Posted by pulkomandy on Wed Jul 14 20:44:33 2021  •  Comments (0)  • 

(yes, I'm writing this article on a Monday. But the title sounded better this way. Whatever.)

As you may know, I'm interested in old computers and sound and music. Recently I was reminded by a youtube video about the Amstrad CKX100, a toy-synthetizer from 1988. I had already heard about it but never had an opportunity to disassemble one, so I didn't know how it was built. Well, this video did just that and got me curious about the soundchip used, the ST M114S. I had not heard about it before and was curious how it worked and if I could possibly connect it to a computer to play some music.

So, a few web searches later, I didn't find a lot, but I found what I was looking for: a datasheet and a research paper from the chip creators, both explaining in some detail how the chip operates.

The research paper is dated from 1985 and mentions that the chip was developped in cooperation with GEM, another synth keyboard manufacturer (who went on to use it in several of their keyboards). It was designed by SGS before merging in ST, so it was the opportunity for me to learn a little more about the Italian side of ST Microelectronics. Previously I had known them mostly for the EF9345 (used in the Matra Alice and the Minitel) and some of the chips used in the Thomson TO8 and MO6 machines, mainly the palette circuit that was developped for the TO9 but later became an off-the-shelf component in ST databooks.

The chip uses an 8KB ROM where sound samples are stored. The samples are in power of two sizes from 16 to 2048 bytes, and are played in a loop to sustain the sound. They use delta coding, which means they encode the derivative of the actual sound. An analogue integrator is used to turn this back into the original signal, which has the advantage of providing some level of smoothing of the output.

The chip does a bit more than just playing the table, however, it can smoothly transition from one sample to another by mixing them together. And it can also play the sample at various speeds by using only one out of two or one out of four bytes (but this risks having a not perfectly balanced signal, which will drive the integrator into saturation).

Moreover, it is indeed designed to be driven by a CPU. It is not a "keyboard-on-a-chip" system that would handle keyboard scanning directly and generate the sounds from there. Instead there is an interface for a normal CPU bus where you can send commands to trigger notes. The commands are made of 8 6-bit words. This may seem a bit strange, 6 8-bit words may have made more sense (especially as most of the values transmitted are indeed 8 bits), but I guess it allowed to save some pins and fit the thing in a 40 pin DIP package.

As a result, this chip was apparently used in some pinball and arcade machines. However, MAME doesn't have an emulation for it yet.

During my search for the Datasheet, I of course looked at ST databooks, and found that there is a larger version called M114A. This one has a 48 pin package, which allows to address 265K of memory instead of 8K. Surely this must allow for much more complex sounds.

Interestingly, the datasheet for the M114S shows a clever hack to increase the ROM space to 16K instead of 8. The chip has an "output enable" pin to signal the ROM when it wants to read a byte. This signal will always trigger twice within a short time since the chip will always read a byte from two samples (remember, it then mixes them together). So, they suggest connecting a flip-flop to this output and resetting it with an RC circuit tuned to a longer delay. The output is then used as an extra address bit, and as a result, the first sample will be from the first half of the ROM, and the second sample from the second half. This simulates the behavior of one of the pins of the M114A, which probably does the same without needing an RC circuit as it knows about the chip internal timing.

Of course I am interested in wiring the chip to RAM. The datasheet says it's possible, but some arbitration will be needed to make sure the M114 and CPU don't try to both access the RAM at the same time. Should I go with dual port RAM? Can I simply block the M114 from accessing the bus when the CPU wants to use it? Maybe I can do some fun tricks where the CPU manages to synchronize itself with the chip and feed it data without using the RAM at all? And, first of all, can I even get one of these chips? There seem to be someone selling them ("used") online, but will they be real chips, or will they be some random other chip being relabelled?

I'm also considering writing an emulator for this chip, just to hear how it could sound like. However, to do anything like that, I think I need ROM dumps from one or more of the original devices using it. At least to make sure my understanding of the storage format is correct. There is a dump from one of the pinball machines using it, but it is using mainly or only PCM samples, and not delta encoding.

Finally I am surprised that this chip was not more popular, for example in home computers. Ok, maybe needing a whole 8K of ROM may be the cause. But it sounds quite nicely, and it would have been interesting to see it alongside the AY3, the SID, and the various options from Yamaha, don't you think?

Programming notes

This information is directly from the datasheet, but here in easier to read HTML format.

All communication with the chip is made with 8 byte commands (only 6 bits in each byte). The bytes must be no more than 128us apart, otherwise the chip considers itself out of sync and the command is aborted.

The command layout is as follows:

2OutputT1 address MSBT2 address MSB
3T2 address LSB
4T1 address LSB
5T1 lengthMode
6InterpolationImmediateOctave Divider
7ChannelTuning LSB
7NoteTuning MSB
  • Attenuation: higher values for lower volume
  • Output: route the channel to one of the four outputs
  • Table addresses: bits A12-A4 of the ROM address to read from
  • Length: number of bytes in T1 sample, from 16 to 2048
  • Mode: various ways to access the two samples, see below
  • Interpolation: Mixing value K. The generated output is S1 * (K + 1)/16 + S2 * (15 - K)/16. A value of 15 plays only table 1, and lower values add more and more of the second sample to the mix.
  • Immediate: apply the new attenuation immediately (otherwise a ramp from the previous value is generated)
  • Octave divider: divide the frequency by two, to play an octave lower
  • Channel: channel on which the command must be run
  • Tuning: finetune the selected note, see below.
  • Note: from 0 to E, 15 possible notes a semitone apart, covering a bit more than an octave. F is reserved for special commands (See below)

The possible values for the tuning:

  • 0 to 5: detune by -6/12 to -1/12
  • 6: detune by -2/1000
  • 7: detune by -1/1000
  • 8: exact note
  • 9: detune by 1/1000
  • A: detune by 2/1000
  • B to F: detune by +1/12 to +5/12

The special commands are not related to a channel. They are globally applied

  • F8: ROM ID mode. The chip will generate addresses 0 to 8 in a loop and send them to the ROM.
  • F9: SSG, enable synchronous mode globally. In synchronous mode, frequency changes are delayed until the next loop point in the sample
  • FB: RSG, disable synchronous mode. Frequency changes happen immediately.
  • FA: RSS, invert the state of synchronous mode just for the next command.
  • FC: Keep the existing frequency from a previously played note.
  • FF: Immediately stop the channel playing.

TODO: SSG and RSG are swapped in another part of the datasheet. Check which one is correct.

And finally the modes affect how the waveforms are accessed:

ModeT1 speedT2 speedT2 length
000 /2 /2 =T1
001 1 1 =T1
010 /4 /4 =T1
011 1 1 max(T1/2, 16)
100 1 /2 T1/2
101 1 1 max(T1/4, 16)
110 1 /4 T1/4
111 1 1 max(T1/8, 16)


It turns out someone already wrote an emulator!

Next steps

I'm looking for ROM dumps of the Amstrad CKX100 (both the samples and the CPU code) so I can learn more about how it uses the chip. Anyone has one and is willing to dump the ROMs?

Gravis Interface Protocol

Posted by pulkomandy on Wed Dec 2 18:47:36 2020  •  Comments (6)  • 

This article has been revised to include fixed and up to date information after I actually plugged the gamepad to an oscilloscope. Now it should be error-free.

Ever heard of the Gravis Gamepad Pro ? It's a gamepad using the old-fashioned PC gameport. It looks quite like the original Playstation controller and has a very solid build quality.

Those of you who know about the gameport limitations will quickly notice that there must be something non-standard about it: there are 10 buttons, while the gameport only allows 4. Even better, you can actually use 2 gamepads at the same time on a single port.

There are several modes accessible with a switch under the gamepad. These are 1-player, 2-player, and GrIP. In 1 player mode, you get 2 axis and 4 buttons. In 2 player mode, you get 2 axis and 2 buttons, and you can use 2 gamepads. In GrIP mode, each gamepad can use all 10 buttons, but this is not compatible with the games expecting a standard joystick.

I have some of these gamepads around, but my PC don't have a gameport anymore. Since I'm not very happy with replacement hardware (I tried the Logitech Precision USB gamepad, but it doesn't look as nice and colourful), and the USB version of the Gravis Gamepad is impossible to find (and less beautiful with the black plastic, I'm thinking about building an adapter for these gamepads to plug them on an USB port. Of course, without opening and rewiring them. Not only this would void the long expired warranty, but I may still want to plug these gamepads to the system they were intended for (my 1995 Pentium 166 MMX).

There is some information on the internet about the protocol, but it's not easy to find. Here is what I could get : a textfile with some info and (originally from http://atrey.karlin.mff.cuni.cz/~vojtech/joystick_specs.txt, which is now offline) and the Linux driver for these joysticks. Since the textfile does not say everything the driver does, here are some notes that duplicate the text file and add the info from the driver.

I checked this with an oscilloscope, so I believe the information to be correct. But I may have missed something.

First, the gameport pinout. It's a SUB-E 15 connector. The following pins are relevant:

  • 1,8,9,15: 5V power (my gamepad accepted down to 3V, below that it stops generating the clock signal)
  • 4,5,12: GND
  • 2,7,10,14: buttons 0,1,2,3
(the other pins are axis 0, 1, 2, 3, they are not used in GrIP mode).

When you use only one gamepad, buttons 0 and 1 are used as data lines. Button 0 is a 20 to 25kHz clock. On each falling edge of this, you can read the state of button 1. Frames are 24 bits long and is formatted as follows:

The frame starts with a start bit, then 5 bits set high. Since the button data is split in 4-bit words with a 0 interleaved, there can't possibly be 5 set bits anywhere else, this makes it possible to detect the start of a frame.

Transmitting a full frame at 20KHz will take about 1.2ms (slightly more than 1.5ms on my test gamepad). This is more than fast enough. It's likely that Gravis drivers on windows only polled the gameport only 20 or 25 times per second (or even less), and waited up to 2ms for a frame start. This was the only way for them, because these gameport buttons are not triggering interrupts.

When there are 2 joysticks connected, the second one uses buttons 2 and 3 exactly the same way. The Gamepad Pro has a pass through connector that swaps buttons 2 and 3 with 0 and 1 for the second device, like any Y-doubler joystick cable does.

I'm planning to use an STM32f3 microcontroller to decode this. The protocol is close to SPI, unfortunately microcontrollers able to handle 24-bit SPI frames are not common. Moreover, the start of frame is hard to detect so synchronization could be a problem. Bit banging the protocol is a better solution, we just have to use the clock line as an external interrupt and read the bits in the interrupt handler.

Développement rapide sur STM32

Posted by pulkomandy on Mon Nov 10 22:53:18 2014  •  Comments (0)  • 

Il y a quelques années de ça (déjà), j'ai fait partie du club robotique de l'ENSSAT. On utilisait pour nos robots des dsPIC30f4011. Afin de travailler rapidement, on utilisait un bootloader permettant de programmer le PIC via un port série, évitant ainsi d'avoir à brancher un PICkit à la moindre modification de code (vu que de toutes façons le lien UART était nécessaire pour tester le code sur le robot). On pouvait même utiliser un adaptateur bluetooth pour faire de l'UART sans fil, pratique pour tester un robot qui se déplace.

Le problème bien connu des bootloaders, c'est que c'est lent. Le lien série a une vitesse limitée et envoyer tout le code pour un PIC peut prendre un certain temps. ça se compte en secondes, mais quand on met au point un bout de code ou qu'on essaie de calibrer un asservissement, ça peut vite devenir très chiant. Notre bootloader était donc capable d'optimiser les transferts en ne reprogrammant que la partie modifiée de la flash. Pour cela le logiciel sur PC est résident, et se souvient du fichier chargé précédement. Ainsi il peut le comparer avec le nouveau et extraire les différences.

Le dit logiciel est d'ailleurs un logiciel libre, il s'agit de RBL. Il inclut également un terminal série pour communiquer avec la carte.

Aujourd'hui, je n'utilise plus de dsPIC30f4011. Par contre, je joue en ce moment avec un STM32f3 et j'utilise toujours un bootloader série. Et le confort de RBL me manque pour plein de petites raisons. J'ai donc essayé de retrouver un confort similaire mais en utilisant une solution plus générique, puisqu'elle repose sur Haiku plutôt que sur Qt ;).

Mon premier problème est de pouvoir partager le lien série entre le bootloader et le terminal. Dans RBL, tout est dans la même application donc il n'y a pas de problème. Le clic sur le bouton "programmer" débranche le terminal, lance le code du bootloader, puis rebranche le terminal.

J'avais commencé à adapter RBL pour l'utiliser avec un NXP LPC1746. Mais avant d'avoir pu finir, j'ai commencé à jouer avec plein d'autres microcontrôleurs, et pour la plupart il existe déjà des outils pour les programmer. Réécrire tous ces outils pour les intégrer à RBL est assez pénible et chronophage.

J'ai donc abordé le problème de façon différente. SerialConnect, le terminal série de Haiku, accepte des commandes de scripting. Cela signifie qu'on peut lui demander, de façon assez simple, de libérer et de reprendre le contrôle du port série (bon j'avoue, j'ai ajouté moi même le support du scripting dans SerialConnect). Concrètement ça donne ceci:

hey SerialConnect delete port
stm32flash ...
hey SerialConnect set port to usb0

Et voilà, on vient de demander à SerialConnect de libérer le port série, ensuite on a lancé stm32flash pour programmer le microcontrôleur, et enfin on prévient SerialConnect que c'est terminé et qu'il peut réouvrir son port.

Il reste un petit problème: stm32flash ne permet pas de redémarrer le CPU pour entrer en mode bootloader. Il faut donc penser à mettre un jumper sur la pin BOOT0 (pour démarrer dans le bootloader et pas la flash), et à appuyer sur le bouton reset. Beaucoup trop fatiguant. La solution est la même qu'on utilise dans RBL, un protocole convenu avec l'application qui permet de la redémarrer et de sauter directement dans le bootloader.

Le protocole est simple: dès que l'application reçoit le caractère 'U', elle se termine. Mon fichier de startup est prévu pour récupérer le contrôle et appeler le bootloader dans ce cas. Il ne reste plus qu'à demander à SerialConnect d'envoyer ce caractère avant de se déconnecter, et le tour est joué. Un simple "make flash" permet de recharger l'application sans avoir à toucher directement à SerialConnect.

Il manque encore l'optimisation de la reprogrammation, qui risque de nécessiter des modifications dans stm32flash. Mais on verra ça dans un autre article, quand mon firmware sera devenu assez gros pour que la différence soit visible.

J'allais oublier, le projet template pour STM32 est sur Github.

Récupérer un Atmel AVR avec FuseBit Doctor

Posted by pulkomandy on Sun Nov 9 23:03:36 2014  •  Comments (0)  • 

Cet été j'ai testé pour la première fois la programmation d'un microcontrôleur AVR8 sous Haiku avec un portage tout frais de la libusb. Malhereusement il restait encore quelques bugs, et je me suis retrouvé avec un AVR avec tous ses fusebits à 0. Impossible de le reprogrammer avec un programmeur ISP classique, soit que le port SPI soit désactivé, soit que l'AVR aie besoin d'une horloge externe que ma carte de développement ne fournit pas.

Fort hereusement une solution existe, il s'agit du Fuse Bit Doctor (attention, page en polonais). Il s'agit d'un montage assez simple à base d'ATMega8 (ou 88 ou 168). Il utilise le mode "high voltage" pour reprogrammer les puces en panne. L'utilisation est très simple: on met l'AVR à réparer dans le socket, on branche l'alimentation 12 volts, et on appuie sur le bouton. En moins d'une seconde la LED verte s'allume et l'AVR8 est restauré dans sa configuration d'usine et fonctionne de nouveau.

Le montage est également assez simple: à part un AVR8 "doctor" contenant le firmware, il comporte 2 boutons, 2 LEDs, 2 transistors, un régulateur, 3 condensateurs et deux douzaines de résistances. Je n'avais pas envie de commander un circuit imprimé ou de tenter d'en graver un, j'ai donc réalisé le montage sur une protoboard 7x9 centimètres. ça rentre juste et il y a la place pour les sockets 28, 40 et 20 pins pour les différents modèles d'AVR qui peuvent être réparés.

C'est donc un montage simple et bien pratique que tout le monde devrait avoir dans un coin en cas de problème. Hereusement que j'ai eu la bonne idée de garder mon dernier ATMega8 encore programmable pour ce montage. Maintenant je peux programmer les fusibles de mes AVR sans avoir peur de tout casser.

Reverse Engineering notes for ATJ227x

Posted by pulkomandy on Wed Oct 30 22:12:24 2013  •  Comments (2)  • 

This weekend I wanted to relax a bit and stop coding, so I decided to resume work on reverse engineering the ATJ227x gadgets.

You may remember I was involved in hacking with the older Actions Semiconductors MP3 players in the S1MP3 project. This never got anywhere, with more powerful hardware now being just as cheap and Rockbox being a more appropriate solution for it. Anyway, Actions Semi is not dead, and they still do some weird system-on-chip stuff. The new iteration is called G1000 and powers some cheap handheld consoles. I can name the JXD 3000, the Kulala K803, the KO W5000 and W6000, and the Juyou A320+ and S430. Never heard of them ? Well you should go buy one of those now. The cost around 30 euros, which is quite cheap, and they all share most of the same hardware: ATJ2279B system-on-chip, 480x272 LCD, USB (they act as mass storage devices), SD card connector audio out (and some of them even have video and HDMI), and a touchscreen.

As usual, besides the very cheap plastic (what did you expect at such a low price? they even added metal weights inside the case so it doesn't feel too light and crappy!), the problem with this devices is the low-quality firmware they are running. This time, instead of a completely homegrown system, Actions Semiconductor went with µC/OS II (no, this is not compatible with Linux nor Android). Anyway, when I got my Kulala K803, there was very few information available on these devices. Now they have spread out a bit more and, more importantly, Juyou made available the firmware update tool and their firmware files. I risked breaking my different console installing that, and, well, it worked. The Juyou firmware is much better than the Kulala one. I think I lost the radio support and maybe some other features in the process, but well, at least I have an useable user interface now (it's PSP-like). I can use this as a MP3 player (Ogg doesn't work with the Juyou firmware it seems), which is already a good thing, and the thing also runs GBA, SNES, Playstation games (slowly).

More important than that, I now have a firmware file to play with! Let's throw binwalk (don't use the Debian package, it's outdated) at it and see what it finds! Well... nothing. Some invalid gzip headers, no strings, no known compression format, just nothing. Not very good, but I know the firmware files for the older z80 devices from Actions were encrypted in some way. So let's try a different approach to this.

It turns out the firmware is encrypted, but fortunately still using the same system as the previous chips. Using the atjboottool done by the RockBox project allows to decode this. Binwalk is much more happy with the result, turns out is it an sqlite database. It stores some metadata, and more interesting, the firmware files. Good thing: I can spot the well-known ELF header in there. The combination of SQLite and ELF makes things much easier to understand. That's nice from Actions. It should also make it much easier to rebuild a firmware file for updating the device, should that be needed. I think it's better to look for the possibility of adding an homebrew loader like this one done for the JXD 3000. I heard the OS structure is different in each firmware version, but maybe there are some ideas I can reuse. It seems the trick to read libs from the mass storage on boot may be JXD-specific, as other consoles (at least the Juyou upgrade guide I've found) use the ADFU firmware upgrade tool over USB instead.

So let's run binwalk again on that interesting img file. Inside there seem to be a lot of ELF files, GIF and PNG pictures, as well as... another sqlite database. The "matrioshka" option in binwalk is starting to make sense. It's a plain FAT32 partition (mount on linux with -t vfat -o loop), however, the partition size is 90MB, yet the file is only 60MB. I can imagine this will create problems if you try to write to it. The structure is quite simple, there is an APP folder with the applications, and a LIB folder with the libs. The other sqlite database is actually for the english/chinese dictionnary app, so it's not very useful for us.

Each application is made of an "app" file which is actually just ELF. Some of them have resources (in res format), a stylesheet (.sty), and sometimes other resources (for example the boot logo app has two animated gif and a startup sound). The RES-file format may be similar to what Actions used on older console, so the code in s1res may be of some use. I have no idea about the STY files, however. There are also "desktop" files which are just lists of strings in different languages for the application name.

In the lib folder, there are only 4 files: applib, style, fusion, and commonui. They are all rather small (less than 500K). A quick look at "readelf -s" shows that there are some source file names information left there. I don't have a MIPS toolchain yet to look at the disassembly and start extracting actual function prototypes, however I can already tell you that fusion seems to be some 2D drawing framework (with rotations, blits, and all that stuff), applib is some kind of system lib (timers, watchdogs, ...), and style is for the UI theming, but seems to export some file I/O functions (fopen, lseek, ...). Commonui seems to be a mix of UI widgets, system stuff, and some of the emulator code (gba_* functions ?). So, no libc or other standard OS stuff here, it seems this is all linked into the apps statically.

The OS itself isn't part of that hidden image. It seems to be built from the other files in the SQLite database. init.exe seems to be interesting, and the best place to look for hooks where to insert the homebrew loader. It's an ELF file again, like all the .so (libs) and .ko (kernel modules). There are also some configuration files in there, which may allow to turn some features on or off (HDMI output, camera input, etc.). I suspect the config is used to pick the right kernel modules and leave the others out. The init.exe has no symbols, so readelf can't tell much about it. It has the usual sections for a C program built with gcc, however, but the complete lack of symbols is strange. I'd expect at least an entry point. That being said, there is a .init section which makes a good entry point as well. strings give a good indication of what it does: initializing low-level stuff (RTC, vram, ...), mounting disks, loading some libs and kernel modules, then running manager.app to run the actual application code. Interesting note: there is a kernel module loaded from /mnt/sdisk, this should be the SD card. Others are run from diska, which may be either the hidden system partition or internal memory. Running strings on the manager.app also gives a fairly good idea of what it does. mnt/sdisk is added to the path so dropping a custom app there may be enough to get it executed in place of the system ones. /mnt/remotedisk sounds useful for development, as well.

The syscfg.sys file is actually where the syscall handlers are. It's NOT an ELF file this time (this seems to be the actual kernel code?) but has helpful strings all over the place. Uli already did the work of analyzing this but he noticed JXD firmware he worked from had different numbers from the others, so I'll have to check if any of this matches mine, and else, find a way to generate the syscall file from any firmware.

If you want to play with this, I have setup a mirror of relevant files. This includes datasheets, Juyou firmware, and update tool (windows only), and I'll add more as I make progress.

Discovering the STM32F3 Discovery

Posted by pulkomandy on Thu Sep 27 18:05:21 2012  •  Comments (5)  • 

So I just got this STM32F3 Discovery board. This is a development board from ST with a Cortex M4 chip, the mandatory leds and buttons, and some accelerometers and sensors.

The main problem is, as often, ST only offers code samples for commercial development environments. And I'm more of an open-source kind of guy. So let's setup some toolchain with free software.

First of all, get the files, this will be more convenient. This archive has the OpenOCD config file, the linker script, startup code, Makefile, and a stupid C code to show it all works (not even blinking a LED!).

Programming the board

That's the easy part. The STM32F3 Discovery has an embedded STLink/V2 interface. A nice thing about it is there are jumpers that allow to use the STLink part to program another device. However, there's a catch: the STLink can only be use to program STM32 and STM8 chips. It's not as flexible as other JTAG adapters.

Unfortunately, STM32F3 support is not part of OpenOCD sources yet. They have a patch set waiting, however:

Do not use OpenOCD 0.6.0 release packages, they don't have these patches in. You will need to get the sources from git and apply the patches above. Then, building OpenOCD is a rather straight-forward process (at least under Linux):

./configure --enable-maintainer-mode --use-stlink
sudo make install
you need to enable access to the STLink hardware for openocd. Create the file /etc/udev/rules.d/99-stlink.rules and add :
ATTRS{idVendor}=="0483", ATTRS{idProduct}=="3748", MODE="0666"
Then test everything is allright. We use the config file for the STM32F4 since OpenOCD doesn't provide one yet for the STM32F3 discovery. They are close enough for this small test, but we'll need a more specific one later on.

Enter the following commands:

openocd -f /usr/local/share/openocd/scripts/board/stm32f4discovery.cfg &
telnet localhost 4444
reset init
reset run
When you enter 'reset init', the STLink should reset the CPU and the ledswill stop blinking. 'reset run' will make it run again and the led should resume blinking. If everything is ok, you're (almost) ready to debug!


The Cortex M4 chip is some kind of ARM CPU, so you need an ARM toolchain. There are several to chose from: Linaro, Sourcery CodeBench Lite, a plain vanilla gcc, and so on. I used Sourcery Codebench, because I already have it installed. But it shouldn't matter anyway: we're not going to use their linker scripts or standard library at all. Just make sure you have some arm-none-eabi-gcc or similar compiler available in your PATH.

Linker script

To make it easier to use different toolchains, it's better to use our own linker script. I derived one from here.

The linker script tells the linker about several things. It defines the memory areas available in the chip, then tells where each section generated by the compiler must go. For example, all code sections are usually allocated in flash memory, while the variables are put in the RAM alongside the stack. Reset vectors usually need to be put at the start of the flash so the CPU knows what to do when booting.

Writing a linker script is not as hard as some toolchain-provided ones make it sound. If you only want to write plain C code, you can get away with something very simple. I plan to use C++ as well, but that doesn't add that much more stuff. I added comments to the linker script, so you should understand what's going on.

Startup code

An usual C program starts with a main() function. However, when working with microcontrollers, there are some things to do before you can reach it. These tasks are performed by the boot code, usually in a function named _start or something similar. This includes setting up some things required by the C language:

  • Setup some hardware so the C code can be used at all (on more complex devices this could include initializing SDRAM controllers or so, on CortexM3 there shouldn't be much to do)
  • A stack, so we can call functions, pass parameters and return (on Cortex M this is done by the CPU hardware as part of the reset handling)
  • Initialize all the global and static variables (so you thought that was done magically?)
  • For C++, call global constructors so the global objects (if any) are in a coherent state,
  • And finally call the main() function, eventually with the argc and argv parameters (but most of the time you don't need that)

Check everything is ok

With a fairly simple program it's easy to look at the final elf file using the

arm-none-eabi-objdump -d
command. This will dump a complete disassembly of the code, so you can check the reset vectors are at the right place as well as the startup code.

The code should start with _start, which will point first to the stack (somewhere in RAM), then to the reset vector which is stored right after it. See the startup.s file to see how that's made.


We'll be using OpenOCD again. While we used the TCL interface to quickly try it out before, OpenOCD is really meant to be used together with gdb. This way, it's possible to debug your code on the chip just like youwould debug any unix application on your PC. How nice is that ?

So, let's load our executable now !

openocd -f /usr/local/share/openocd/scripts/board/stm32f3discovery.cfg &
telnet localhost 4444
reset halt

flash erase_sectors 0 0 127
flash write a.out 0x8000000

So, the first step is to reset the CPU and halt it to make sure it isn't runnning code from the flash while we're erasing it. Then, we erase the flash, bank 0, sectors 0 to 127 (that's the whole flash of this chip). Finally, we write our new code. Notice the 0x8000000 offset: while the code is executed from address 0, the flash must be written from address 0x8000000. This is related to the way the STM32 chip can boot. Depending on the state of the BOOT0 and BOOT1 pins, the address 0 will be mapped to eitehr the flash, the SRAM, or the system ROM holding ST bootloader. But writing can only occur at the "e;real"e; flash address.

Now that our program is flashed, let's attempt to debug it. Exit the openOCD telnet prompt, but leave OpenOCD runnning. Now connect to it with GDB:

target remote localhost 3333
file a.out
break main
First we connect to the OpenOCD server through the GDB port. Then, we load the file to get the debugging symbols from it. The first stepi command is to sync gdb with OpenOCD. From then on, we can set breakpoints, and run/debug the program as usual. Happy hacking!

Programming ARM chips with OpenOCD in Debian

Posted by pulkomandy on Sun Oct 9 14:31:43 2011  •  Comments (0)  • 

I bought an LPCXpresso board from NXP for toying around. Unfortunately, the JTAG interface built in this board can only be used with codeRed tools, and the free edition has a limit of 128k of flash memory. I want to use freely available tools, so I cut the board to remove the JTAG part and plugged in my Altera USB-blaster instead.

However, I quickly noticed that the version of OpenOCD built in Debian doesn't work well with it. Searching the web shows it's a bug in libftdi, and you have to use the closed-source libftd2xx instead. The installation works fairly well, just get libftd2xx from FTDI website, copy the so files in /usr/local/lib, then download and compile OpenOCD.

LibFTD2xx install

cd libftd2xx1.0.4
cp build/x86_64/libftd2xx.so.1.0.4 /usr/local/lib
pushd .
cd /usr/local/lib
ln -s libftd2xx.so.1.0.4 libftd2xx.so
cp ftd2xx.h WinTypes.h /usr/local/include

OpenOCD 0.5.0 install

./configure --enable-usb_blaster_ftd2xx
# ... fix a warning as everything is built in -Wall mode ...
# there seem to be a bug with OpenOCD tools, where it forgets the -lftd2xx here. Do it ourselves :
gcc -std=gnu99 -g -O2 -Wall -Wstrict-prototypes -Wformat-security -Wshadow -Wextra -Wno-unused-parameter -Wbad-function-cast -Wcast-align -Wredundant-decls -Werror -o openocd main.o  ./.libs/libopenocd.a ../jimtcl/libjim.a -ldl -lftd2xx
sudo make install

Adaptateur souris AMIps2 pour Commodore Amiga et Atari ST

Posted by pulkomandy on Thu Nov 4 20:18:17 2010  •  Comments (0)  • 


Ce circuit de taille réduite permet de connecter de faon transparente une souris ps/2 à un ordinateur Amiga ou Atari ST. Il détecte automatiquement chacune de ces deux machines afin d'envoyer les signaux correspondants.

(merci Arklif pour les photos)

Une version utilisable sur les ordinateurs Thomson TO est également disponible.

Une version du circuit spécialement adaptée pour recevoir une alimentation 5v externe est disponible. Elle permet d'utiliser une souris optique qui consomme trop d'électricité par rapport à ce que le port souris d'un amiga peut fournir.

Ce montage est adapté de celui disponible ici.

Informations techniques : le montage est réalisé autour d'un PIC 16f628 et comporte très peu de composants : 3 résistances et un condensateur.

Voici le schéma du circuit (rsolution 300 dpi), et le projet piklab contenant le code source en assembleur.

Projet piklab Projet eagle

Prix : 20 euros, expdition comprise

ATTENTION : Problème de détection Atari/Amiga

certains utilisateurs sur Amiga 1200 et 4000 se sont apperçus que l'adaptateur se croyait sur Atari au dmarrage de la machine. Cela est probablement du à de mauvaises valeurs de composants.

Il existe hereusement une solution simple pour forcer le mode Amiga : il suffit de couper une piste de l'adaptateur comme suit.

couper la piste entre la broche 6 du PIC et la resistance.

Dans ce cas, l'adaptateur fonctionnera toujours en mode Amiga et ne pourra pas être utilisé sur un Atari.

Des trucs AVR

Posted by pulkomandy on Mon Oct 18 22:36:51 2010  •  Comments (0)  • 

Je n'avais pas encore mis de news ici, mais les adaptateurs clavier amiga fonctionnent et sont en vente au prix de 20€. Contrairement à AmiPS/2, Amikey2USB est vendu avec un boîtier.

Comme les Atmel AVR marchent plutôt bien, j'en ai profité pour faire aussi une version ps/2 vers usb de l'adaptateur, ainsi qu'une carte pour gérer des boutons dans une borne d'arcade (encore en prototype pour l'instant).

En tout cas, je n'ai pas toujours le temps de maintenir ce site à jour, et j'utilise maintenant mon installation de Trac. Il y a donc d'autres façons de me surveiller...

  • La liste des projets. Pour l'instant tout ce qui est électronique est dans le projet avrstuff. Mais d'autres pourraient apparaitre.
  • Les flux RSS: ils sont également disponibles dans chaque projet de Trac, mais je trouve ça plus pratique d'avoir une page avec un apperçu complet.

D'autres projets sont en cours, mais je vous en dirai plus seulement une fois que ça commencera à fonctionner.

News en vrac

Posted by pulkomandy on Mon Feb 22 21:55:11 2010  •  Comments (0)  • 

Bon, il n'y a pas eu de mises jour dans ce coin depuis un certain temps, donc en voil quelques unes...

  • J'ai enfin fini de souder mon USBasp. Ce programmeur permet de graver des puces atmel AVR. a me changera un peu des PICs qui ont un assembleur assez illisibles et ne sont pas trop fait pour le C...
  • Ce programmeur va me permettre de travailler sur l'adaptateur permettant de brancher un clavier amiga (4000 ou 2000) sur une machine en USB. Mais j'ai fait quelques erreurs de gravure de la carte qu'il va falloir rattraper.
  • La version interne de l'AmiPS2 est maintenant officiellement disponible. Mme prix que la version externe, lgrement plus petite, et avec deux trous de fixation pour l'accrocher ou vous voulez.
  • Prochaine tape : construire un programmeur de CPLD qui va me servir entre autres, pour le projet ReACID. Mais aussi par exemple pour fabriquer des UltraSatan ou d'autres machins un peu compliqus dans ce genre.

Cela dit, je suis assez pris par les projets scolaires, donc tout a ne sera pas fini "la semaine prochaine". Plutt pendant l't. Les AMIps2 sont toujours disponibles (il en reste aussi quelques uns en version externe). Le reste arrivera petit petit.

Lecteur de disquettes Floppy-1 pour Amstrad CPC et Amstrad Plus

Posted by pulkomandy on Mon Jul 6 14:06:19 2009  •  Comments (0)  • 


photo du Floppy-1

Un lecteur de disquette pour les ordinateurs Amstrad CPC(+).

Vrai signal "ready", switchs de changement de face et de forage en A, alimentation 5v externe.

3 versions avec des connecteurs diffrents : CPC Old, CPC Old Centronics, CPC Plus.

45 euros, expdition comprise

Adaptateur joystick 4joy pour Amiga

Posted by pulkomandy on Mon Jul 6 14:04:33 2009  •  Comments (0)  • 


Cet adaptateur permet de connecter deux joysticks supplémentaires sur le port parallèle de votre Amiga.

Il est utilisable avec les jeux suivants :

  • Dynablaster
  • Gauntlet II (US Gold)
  • International Soccer (Microdeal)
  • Kick Off II (Anco)
  • Knock Out 2
  • Leatherneck (Microdeal)
  • Projectyle (Electronic Arts)
  • TV Sports Basketball (Cinemaware)

L'adaptateur coûte 15 euros, expdition incluse.

Afficheur a LEDs ledmeter pour tout ordinateur equipe d'un port parallele

Posted by pulkomandy on Mon Jul 6 14:01:55 2009  •  Comments (0)  • 


ledmeter ledmeter ledmeter ledmeter ledmeter

Brochage du connecteur CON1:

  • 1: Data 4
  • 2: Masse
  • 3: Data 3
  • 4: Data 2
  • 5: Data 1
  • 6: Data 0

Le ledmeter est constitué de 32 DELs et se connecte sur le port parallèle de n'importe quel PC. Le circuit est plutôt simple puisqu'il s'agit simplement de démultiplexeurs (et d'une porte NON). Ceci permet une programmation également très simple: pour allumer une DEL, il suffit d'envoyer son numéro sur le port parallèle. En théorie, il est possible de cabler jusqu'à 2565 diodes sur un port parallèle. Cependant ma version n'en comporte que 32 pour des raisons de place disponible.

Une petite vidéo de démonstration est disponible ici.

Vous pouvez télécharger le projet eagle et le code source du programme pour linux.

Si vous voulez construire une version de ce ledmeter, si vous améliorez le programme, merci de partager vos idées et de m'envoyer des photos de vos créations.

ZenBox : 2 lignes, 1 telephone

Posted by pulkomandy on Fri Jun 27 23:12:37 2008  •  Comments (0)  • 

Zen PhoneBox

Il s'agit d'un boîtier permettant d'utiliser deux lignes teléphoniques (dans notre cas une ligne freebox et une ligne france téléom) avec un seul téléphone. Le circuit a été conçu par VieuxGeo, vous pouvez avoir pas mal d'infos sur son site: ICI