⢠PSG / AY-3-8910 ā Arkos Tracker 3 preferred (we can talk formats)
⢠The game will be released for FREE
I can pay for the tracks, or credit you in the game, whatever suits you best.
#MSX #chiptune #chipmusic #retrogaming #AY38910
So, annoyingly after thinking I might have had a bit of a breakthrough, it turns out I was chasing my tail and it seems like I'm back to square one...
I'm going to have to have a break from this for a bit, as I'm running out of options at the moment.
https://diyelectromusic.com/2026/05/24/ay-3-8912-8910-hardware-emulation-part-3/
AY-3-8912/8910 Hardware Emulation ā Part 3
This continues my series looking at hardware emulation of the AY-3-8912/8910:
This post picks up with an attempt to rebuild the firmware from source in an attempt to figure out what is going on.
Spoilers: At the end of it, it still doesnāt work thoughā¦
Warning! I strongly recommend using old or second hand equipment for your experiments. I am not responsible for any damage to expensive instruments!
ICSP Header
The first thing to do is to add the ICSP header to my AVR-AY. Unfortunately, as I mentioned in Part 2 I got the pinout back to front. But this can be easily accounted for by soldering the ICSP header onto the underside of the board.
I decided this would work best with a right-angled 2Ć3 pin header, which also means it sits nicely under the bent-over capacitor.
An easy check is to use the Arduino environment to download a blink sketch. As Iām using my USBasp again, I need to select that under āToolsā -> āProgrammerā, then it is possible to use āUpload using Programmerā to load a sketch. This can be found under āSketchā or as shown below, using the shortcut CTRL-SHIFT-U.
All being well, pin 13 should be toggling on and off, albeit at a slighter faster rate than expected ā this is running off a 27MHz crystal rather than a 16MHz of course.
Note: LED_BUILTIN = D13 = PB5 = BC2 = ICSP CLK on this board, so that is fairly easy to probe with a scope, or even temporarily add in LED.
AVR Development
In every other case, Iāve never bothered to get into raw AVR development. Iāve found I can do everything Iāve been interested in doing via the Arduino environment.
Unfortunately one thing the Arduino environment wonāt do is assembly. Plus it will always add in some bootstrapping code prior to running your setup() routine and it has some housekeeping code inbetween each call to the Arduino loop().
There are a number of options for including some assembler in an Arduino sketch, but it is quite limited and doesnāt scale to an entire program.
One option is to assemble it outside of the Arduino environment and then include it in the final build. But that is all a bit of a faff, so Iām dropping back to a non-Arduino build envirnment, and traditionally that meant using Atmel Studio.
But this is no more. When Microchip acquired Atmel in 2016, this was renamed Microchip Studio. But even that is now deprecated for new designs. But it is still available, so Iām starting with that.
Another option is winavr. I might return to giving this a try laterā¦
LED Flash in Microchip Studio
To check everything is running with Microchip Studio, I opened one of the example projects, filtering for ATmega328, āmegaAVR led example ā ATmega328P Xplained MINIā. I think this is for one of their own dev boards.
This gives me a whole pile of code, but the only bit Iām interested in is in src/mega_led_example.c. Everything else in src/ASF and src/config I think is related to the dev board and examples, which Iāve mostly ignored.
I changed the provided code, which would flash an LED on a button press, to the following:
#define F_CPU 27000000ULLED0 and LED_On/Off are defined for the board, and in this case map onto PB5 which is the same as LED_BUILTIN being D13 for an Arduino Uno.
I first played save with F_CPU = 16MHz, but actually once everything was up and running, it seemed quite happy for me to set it to 27MHz for the delay to be accurate.
So, this now builds, but now to download itā¦
Microchip Studio and USBasp
There are a number of programmers supported within Microchip Studio, but USBasp isnāt one of them. To be able to use it, it has to be added as an external tool.
But before that can happen, you have to make sure youāre in Advanced Mode.
When installing, there is an option of running in Standard or Advanced mode. I choose standard, and consequently couldnāt find most of the things being talked about online in conjunction with USBasp and Microchip/Atmel Studio!
Once changed to Advanced Mode, under āToolsā there is an option for āExternal Toolsā. Once selected, a new tool setup is entered for USBasp.
This has to use the same avrdude setup as described in Part 2, but the filename has to link into the paths that Microchip Studio will use.
Everything else is left as you see it above. When saved, there is now a new entry under āToolsā which can be used to download directly via USBasp.
Note: debugging is not possible, so the whole āDebugā set of menus is ignored.
At this point I can use āBuildā -> āBuild Solutionā and then āToolsā -> āUSBasp-ATmega328Pā to build code and get it running.
Microchip Studio Raw Assembler
Now onto the main reason for doing all this ā can I build and run the assembler for the AVRAY?
Turns out that is one of the supported options. On creating a new project (curiously, for a C/C++ project there is an option to import an Arduino sketch), choosing assembler gives:
Then Iām asked to choose a MCU, so select ATmega328P and then I am provided with the following:
But actually when I went to get the source, there is already an Atmel Studio project file included (this is the source from: https://github.com/Yevgeniy-Olexandrenko/avr-ay-board/tree/main/firmware/v1.0/sources
On opening this project file, it requires the downloading of an additional pack: Atmega_DFP. I told it to download the specific version requested. But it seems to have ignored me and downloaded the latest one.
In the project properties I had to change the device from ATmega48PA to ATmega328P.
In order to avoid the need for an EEPROM configuration file (which requires the command line avrdude command as described in Part 2) I fixed the code to always assume no serial interface, always parallel interface, and 27MHz operation:
RESET:Then I used PD1 as a debug OUTPUT pin rather than its usual TX function. Whenever this was required, the following code would be used to set or clear the OUTPUT:
; SetUsing this at the start of the MAIN_LOOP, then for ISR_INT0 and ISR_INT1, I can see that when I manually trigger BC1 or BDIR that the interrupt routines are indeed being called as required. There are two return points in each ISR. They basically have the following structure:
ISR_INT0: Triggered on BC1I can also see that the main loop does utilise most of the CPU time between the PWM sample period.
Note: When looking at pins PB1-PB3 directly (i.e. before the filter circuit) I can see the PWM short pulses occuring, so I know all register initialisation for PWM is happening correctly too.
A note on initialising the interrupts:
; --------------------------------------------------------------------------The comment states āfallen edgeā but the value 0x0F written to EICRA will set up the interrupts on the rising edge. Given that comments elsewhere in the ISRs discuss waiting for the signals to clear, I believe rising edge is correct.
For example, in ISR_INT0, triggered on a rising BC1, it will then wait for BC1 to clear before returning.
At this point, Iām throwing all timings to the wind and adding instructions to instrument the interrupt routines as follows:
ISR_INT0: Triggered on BC1The idea is to attempt to capture what the AVRAY thinks is going on with respect to BC1/BDIR. Here is a trace of the first access.
Yellow is PD0/BC1 and blue is PD1/BDIR. We can see PD0 going HIGH, hence an INT0 indicating BC1 was detected, followed by PD1 going HIGH which means INT0 has jumped to LATCH_ADDRESS, followed by both going LOW showing it is complete and the return from interrupt.
Then we see BDIR going high with no signal for BC1, so this means INT1 has triggered and a register write is occurring.
Then we see the LATCH_ADDRESS pattern repeat. In fact, including the first one, this repeats 10 times, which corresponds to my test code attempting to initialise 10 registers on startup.
But although the test code is using the same algorithm to latch the address (BC1=BDIR=HIGH) and then a register write (BC1=LOW, BDIR=HIGH) the emulator code isnāt āseeingā any more register writes.
It turns out that the first write is the only one seen by the emulator at all. In the following trace, we can see the ten initialisation writes happening, then a short pause as the Arduino returns from the setup() code and starts the main loop(). Then there is regular scanning of a single AY register in the Arduinoās loop. The first trigger is the only one that shows the write happening at all.
So to me, this implies that INT1 has somehow stopped functioning. I need to add in the traces of the actual BC1 and BDIR signals to be sure they are still happening though, although I see no reason to think they wonāt be.
Ok, this is illuminatingā¦
Dark blue is BC1 and purple is BDIR. As we can see here, it goes HIGH and then stays HIGH, well forever. I guess the first write is picked up as the INT0/INT1 interrupts I guess are queued up?
At this point I pulled the AVRAY out whilst it was running, and guess what? BDIR was still HIGH. So looking back over my test code, and I spot this:
#define BDIRLOW {PORTC &= 0xF7;} // A2 LOWAnyone? All together nowā¦
Sigh. Yes, that 0xF7 should have been 0xFB. Or better yet, (~0x04).
So now I finally can see that the interrupts are, indeed, working as expected.
Try Againā¦
So at this point, I went back to the original 328 firmware, EPROM configuration and fuse settings, figuring that my test writes to pins isnāt going to help anything working.
And it still doesnāt work. Big sigh.
At this point Iām going to have to leave it again, because all Iāve really proved is that I canāt be trusted with both sides of a two-part systemā¦
Kevin
#arduino #atmega328 #avr #ay38910 #microchipStudioAY-3-8912/8910 Hardware Emulation ā Part 2
Having explored how an AVR can be used to emulate the AY-3-8912/8910 in AY-3-8912/8910 Hardware Emulation I wanted to have a go at using the very common ATMega328P to do the same. But rather than wire things up on breadboard, I put together a quick PCB to allow me to do some experiments.
Spoilers: This isnāt working yet!! Read on for where Iāve got to, but Iāll need to come back to this at some point.
Warning! I strongly recommend using old or second hand equipment for your experiments. I am not responsible for any damage to expensive instruments!
If you are new to electronics and microcontrollers, see the Getting Started pages.
The Circuit
This is essentially the circuit from here: https://github.com/Yevgeniy-Olexandrenko/avr-ay-board
But with an ATMega328P rather than the suggested ATMega48PA (more about that in part one here: AY-3-8912/8910 Hardware Emulation). Iāve included headers for both the AY-3-8910 and AY-3-8912.
Iāve kept the same usage of ATMega ports, which map onto IO for the ATMega328P as follows:
AY-3-8912SchematicATMega328P PORTATMega328P PinArduino EquivalentD0-D5DA0-DA5PC0-PC523-28A0-A5D6-D7DA6-DA7PD6-PD712-13D6-D7A8A8_CIPOPB418D12BC1BC1PD24D2BC2BC2_SCKPB519D13BDIRBDIRPD35D3CLOCKCLOCKPD46D4RESETRESETPC61RESETTESTN/CIOA7-IOA0N/CCPWM_CPB216D10BPWM_B_COPIPB317D11APWM_APB115D9A9_CFG0PB014D8CFG1PD56D5RXPD02D0TXPD13D1VCCVCCVCC7, 20VCCGNDGNDGND8GNDThe only change is Iām not connecting TEST to anything. Iāll have to see if this becomes an issue laterā¦
The circuit calls for overclocking the ATMega328P to 27MHz (again more discussion on this in the first part).
Iāve included breakout headers for ICSP and a serial header.
I have also swapped the oscillator to a crystal using a common configuration Iāve seen on many DIY Arduino-style boards using an ATMega328P.
Rather than put together two boards, one for the 8912 and one for the 8910, Iāve also put together a simple adaptor circuit to allow one to plug into the socket for the other.
The schematic essentially just maps the signals from one footprint onto the other.
The only slight complication is that /A9 for the 8910 doesnāt exist on the 8912, so Iāve left in a jumper to provide the option of tying this to GND or VCC should the need arise. This should allow the larger 8910 to be used in the place where a 8912 is required whilst still enabling the 8910.
PCB Design
I did wonder quite how much of a 28 pin DIP could fit inside the footprint of a 28 pin WDIP and still keep through hole components, but I didnāt have to wonder for long to see it wasnāt really going to work.
So as this is basically just for messing around I went with the format as shown. This way, round-profile pin headers can be used on the underside for the AY footprint if the board is to replace a genuine device. Alternatively normal pin headers or sockets can be used on the topside if jumper wires are going to be used to hook this board into another PCB.
The two CFG jumpers are solder bridges (default not connected) on the underside of the board. Iāve also listed the Arduino versions of the AVR pins used on the underside too.
For the converter board, Iāve left the /A9 jumper as standard pin headers. With hindsight Iām not sure when this would be wanted to be tied high, as presumably that would disable the chip. When plugging a 8912 into a 8910 socket, anything expecting an 8910 and using /A9 as part of the addressing scheme would require some additional logic before mapping it onto the smaller 8912.
Errata
The ICSP header is swapped to what is required. This will still work as long as the header is populated on the reverse of the boardā¦
From the top/silkscreen, the header has the following pinout (viewed from the top, ATMega328 on the left).
RESETGNDCLKCOPICIPOVCC (square pad)Bill of Materials
AVR-AY Emulator Board:
AY-3-8910 to 12 Converter:
AY-3-8910 to 12 Converter Build
This is a relatively straight forward build, but depending on the DIP sockets used it might be necessary to doctor the socket slightly to sit neatly over the soldered pins.
Order of build:
If the converter is from a 8912 socket to a 8910 device, then the /A9 jumper or a solder link will have to be configured, presumably connecting it to GND to make it permanently active.
One note of caution ā the pins I was using are not particularly robust, so when removing the adaptor from its socket, I managed to break one and had to replace it, which wasnāt easy.
But apart from that, it works!
AVR AY Board
As already mentioned there are a number of configuration options for the 28-pin AY-3-8910 emulation as illustrated below.
The first two are designed for jumper wire connections. The third shows the use of pins which would allow the board, space permitting, to be inserted into a AY-3-8910 socket on an existing board.
These headers will be soldered on last, but it is worth deciding in advance what configuration will be required.
Iāve chosen not to populate the UART and ICSP headers, and am using round pins so that this can hopefully replace an AY-3-8912. But at the moment all my test boards are built for the AY-3-8910, so Iām also having to use the converter, which has led to the following stack of boards!
ATMega328P Programming
The stand-alone ATMega328P chip cannot be programmed directly from the Arduino IDE with this code as it stands. Instead the following are required:
The firmware should be downloaded from https://github.com/Yevgeniy-Olexandrenko/avr-ay-board.
Update: I ended up using a slightly different firmware and configuration ā see laterā¦
Iām using v1.0 of the firmware and have downloaded the binary firmware and the 1.75MHz configuration. I now have the following files:
C:\Kevin\Temp> dirTo program the ATMega328P requires the following instructions to get the code into flash, the configuration into EEPROM and to set the fuses for the MCU:
C:\Kevin\Temp>avrdude -c USBasp -p ATMega328P -U flash:w:avr-psg.hex:iThe error ācannot set sck periodā is apparently pretty common especially with USBasp clones, and can be ignored.
The three fuse settings come from the original AVR-AY firmware (here) in the readme as follows:
ATMEGA328 ===================================================But where the fuse settings for lfuse = 0xEE, when decoded from the ATMega328P datasheet and an online AVR fuse calculator here: https://eleccelerator.com/fusecalc/fusecalc.php?chip=atmega328p means the following:
0xEE = b1110 1110Which from the AVR fusecalc site maps onto:
However, following through the settings in the datasheet, it is similar but slightly different, giving:
But Iām not using a ceramic resonator, Iām using a crystal oscillator, so I think I need the mode:
There is no ā1KCKā for the crystal oscillator settings, so Iāll have to use 16KCK I guess?
This is what gives me the 0xDF value Iāve used:
0xDF = b1101 1111Actually, this wasnāt working with either 0xEE or 0xDF, so I decide to try to turn off BOD and went with āslow rising powerā (CLKSEL0+SUT = 1+11) which gave me the fuses:
lfuse = b1111 1111 = 0xFFBut that isnāt working eitherā¦
The AY891x Library and BCn/BCDIR control
Eventually, I remembered reading about the control signals with the library that was designed for use with that test board. It states the following (here):
āWhile the PSG has tight timing requirements, it is possible to use digitalWrite() by using all three bus control signals (BDIR, BC1, BC2) and cycling through an extra state when reading and writing the chip registers.ā
But the emulation is ignoring BC2 (more here), relying instead on the ATMegaās two IO interrupt pins INT0 and INT1 on D2 and D3, to trigger on BDIR and BC1. This means I had to ditch the library and instead switched over to my own PORT IO driver as described here: Arduino and AY-3-8910 ā Part 3.
Resetting the fuses as before, unfortunately it still isnāt working.
At this point I loaded on a simple tone() function on one of the IO pins using the Arduino IDE then set the fuses again as above. I can definitely see that the frequency for the tone() output is almost twice as high as when the ATMega328P is plugged into the Arduino, so the 27MHz crystal is certainly having an effect compared to the Unoās original 16MHz.
I can also see the 105kHz PWM carrier frequency on all three PWM output pins, but the peaks are so narrow, these must be responding to a level 0 output which implies all code is working, but there are simply no register writes getting through.
So, in summary, I think the code on the emulator is running fine ā so why isnāt it responding to register writes?
An Epiphany?
At this point I left things for a bit and came back to it all a few days later.
I was chewing over why the register writes didnāt seem to be getting through, so at this point I think the handling of BC1 and BDIR are key. The next things that I tried:
At this point Iām suspecting the interrupts arenāt getting through (remember BC1 and BDIR are triggered off the external interrupts), so Iām contemplating two things:
But this has got me wondering about build differences for the two devices ā what might be different between the ATMega48 and ATMega328P. Would rebuilding from source for the ATMega328P sort it out?
Looking at the original code, I can see there are many different binaries for the different chips. For the repository Iām using there is just one.
Looking in the two chip datasheets, I can see that the INT0 interrupt vector is different ā it is 2 (address 0x001) for the 48 and whist it is still 2 for the 328P, the address is 0x0002. From the 48 datasheet:
āEach interrupt vector occupies two instruction words in ATmega168, and one instruction word in ATmega48 and
ATmega88.ā
From the 328P datasheet:
āEach interrupt vector occupies two instruction words in Atmel ATmega328P.ā
Looking at the suggested implementations of the vector tables, they are shown as follows:
// ATMega48 vector tableSo presumably one is a relative jump (rjmp) which is a single word (16-bit) instruction, vs an absolute jump which is a two-word (32-bit) instruction.
With hindsight is seems obvious Iād need to rebuild for the ATMega328P, but the initial talk of compatibility lulled me into a false sense of security!
There is no build for the 328P in the listed repository, but going back to the original avr-ay source, there are builds for all supported MCUs, each with variants covering:
There are configuration options for:
Iāve now downloaded:
avrdude -c USBasp -p ATMega328P -U flash:w:AY_Emul_260_3ch_m328_ay.hex:iBut unfortunately it still isnāt workingā¦
I did notice in the original source, a number of conditional assembler code, based on the initial configuration of MCU_TYPE. But most of it is of the form āif MCU_TYPE==0ā which is giving alternative code for the ATMega8. There is one piece of code that implies something different for the ATMega48:
; get byte 0 from EEPROM, check value > 0 or skip USART initialization if value = 0I also note that the vector table is all relative jumps:
.csegBut as each entry has its own origin statement, one presumes that these are correct for the MCU type.
Double checking the hex records for my chosen firmware, and adding some expansions and annotations, I can see:
// Format:So yes, it would appear that the vectors in the vector table are indeed on the expected 32-bit boundaries which matches and it has values for vectors 2 and 3, so INT0 and INT1. Vector 1 is RESET.
One oddity, each record is only 2 bytes long, so I guess it is assuming that the missing bytes will be zero? Really, the full records should perhaps be:
:04 0000 00 88C00000 B4 // Needed to recalc CRCI donāt know the algorithm for calculating the CRC, but I donāt need to. When attempting to download via avrdude any CRC mismatch is reported, detailing what value was expected which allows me to set the correct value for each line at a time!
But as these are instructions rather than addresses themselves, maybe it would be fine. If the PC hits this address, then the instruction will be (presumably) a rjmp which is only two bytes and all would be fine.
But regardless, unfortunately this still isnāt working. Iām now at quite a loss as to what to try next.
I did go back and look at the original firmware I was using and it has the following:
:06 0000 00 70C039C045C0 CCSo I donāt see how this would work on an ATMega328P at all as each vector is only half the expected size.
The reset vector is probably ok, as the first two bytes will be read as a ārjmpā instruction and presumably the next two bytes ignored. But INT0 and INT1 will be jumping off into who-knows-where.
This would match the evidence that the board seems to get initialised but no register writes are processed.
So this at least does confirm that the original firmware was no good for me.
Conclusion
Iāve got to draw a line under this for now. Iām going to hit publish on this post as is, and put this aside for a bit.
Some possible future directions:
But for now, this one is on pause.
And Iām still annoyed about the error in the ICSP pinoutā¦
Kevin
#arduino #atmega328 #ay38910 #ay38912 #emulation #MakerFail #pcbsAnd for a fun comparison here is the same with four AY-3-8910s...

But I have now published my walk through of part of the AVR emulation of AY-3-8910/8912 devices.
Fascinating stuff.
https://diyelectromusic.com/2026/04/06/ay-3-8912-8910-hardware-emulation/
AY-3-8912/8910 Hardware Emulation
The 40-pin AY-3-8910 devices Iāve been playing with are no longer newly available, but they are pretty available if you are happy with a certain questionable quality (more on that here: Arduino and AY-3-8910).
But the slightly shorter version (with fewer general purpose I/O pins), the 28 pin AY-3-8912, seems a lot harder to find, despite being widely used at the time. At least, to find on its own ā i.e. not already soldered onto a circuit board. There is apparently also an even smaller AY-3-8913 in 24-pin format and a few other lesser used options too. But the 8912 is the variant most often found in the ZX Spectrum 128, Amstrad CPC, and many home computers from the time.
A key modern option then is emulation and there is a very capable AVR emulation of the sound generator online including some on PCBs that directly fit within the 28-pin footprint of the original.
One is Yevgeniy-Olexandrenkoās avr-ay-board for the AY-3-8910, AY-3-8912 and YM2149F devices, with a 8912-compatible DIP-28 PCB design using an ATMega48.
Another is published on https://www.avray.ru/, but that appears to be the firmware only. There is a board that uses this firmware built for an ATMega8P here and another for a two-device (dual AY-3-8912 for 6 channel support is often called āTurbosoundā) here.
I donāt believe either of these approaches emulate the general purpose IO pins of the 8912/8910, which might be an issue using them āas isā in a retro system. I know the ZX spectrum 128 uses the IO for example.
Some options for replacing original AY-3-8912 devices:
But perhaps my favourite so far is the slightly random, ābuilding an AY-3-8910 out of discrete logicā that I must have a proper look at, at some point: https://github.com/mengstr/Discrete-AY-3-8910
This post looks at how AVR emulation of AY devices works in a little more detail and maybe take some starter steps to reproduce my own.
Warning! I strongly recommend using old or second hand equipment for your experiments. I am not responsible for any damage to expensive instruments!
If you are new to microcontrollers, see the Getting Started pages.
AVR-AY-Board
The avr-ay-board is a fully open source design and can use an ATMega48, 88, 168 or 328. The ATMega328P is very commonly used on an Arduino Uno or Nano.
Full details, including a schematic, gerber files, BOM, and firmware are available here: https://github.com/Yevgeniy-Olexandrenko/avr-ay-board.
It shares a lot of firmware heritage with the source available from https://www.avray.ru/. Up until Feb this year there was a link back to the original source, but that has since been removed and it appears to have mostly diverged some time in 2022. There is a list of differences here, but much of the discussion that follows would probably apply to both versions of the code.
The only difference between the ATMega48, 88, 168 and 328 is the amount of memory. They are named for the amount of flash memory ā 4K, 8K, 16K, 32K respectively. But otherwise they are functionally identical. Here is the key data from the datasheet:
Note that the ATMega328PB is an enhanced version of the ATMega328P which itself is a slightly lower power (as I understand things) version of the original ATMega328. Application note āAT15007: Differences between ATmega328/P and ATmega328PBā lists the full set of enhancements, but it includes additional UART, SPI, I2C, and timers, although it is essentially backwards compatible with the 328/328P.
All of this means that a standard Arduino Uno or Nano might be able to run the bespoke AY-3-8912 emulation firmware and with the appropriate pin connections might also be able to emulate an AY-3-8912 in another system. Naturally it will be physically larger than the original chip, but electrically it should all work fine.
The Circuit
The original ABR-AY-Board is relatively straight forward. The full schematic is available in the GitHub repository and shows the following:
There used to be a detailed āusageā section on the GitHub but that has since been removed, but from the published schematic (v1.5) the pins are accessed and mapped as follows.
AY-3-8912SchematicATMega48PArduino EquivalentD0-D5D0-D5PC0-PC5A0-A5D6-D7D6-D7PD6-PD7D6-D7A8MISO_A8PB4D12BC1BC1PD2D2BC2SCKPB5D13BDIRBDIRPD3D3CLOCKCLOCKPD4D4RESETRESETPC6RESETTESTMOSI_PWM_BPB3D11IOA7-IOA0N/CCOUT_C / PWM_CPB2D10BOUT_B / MOSI_PWM_BPB3D11AOUT_A / PWM_APB1D9CFG0PB0D8CFG1PD5D5RXPD0D0TXPD1D1VCCVCCVCCVCCGNDGNDGNDGNDThere is a UART header (TX, RX, VCC, GND), ICSP header (MISO, MOSI, SCK, RESET, VCC, GND), and two configuration jumpers (CFG0, CFG1).
One point that might cause issues mapping over to an Arduino Uno or Nano is that the avr-ay-board has a 27MHz oscillator, whereas the Arduino only runs at 16MHz. That will almost certainly need some looking at.
The Clocks
So about that 27MHz clock. The default Arduino has a 16MHz oscillator so could this run on an unmodified Arduino?
Looking through the code, there seems to be one specific mention of the CPU frequency:
; --------------------------------------------------------------------------In the commented out code, there is reference to 27000000. But then that appears to be replaced with code that is reading the PWM frequency from EEPROM.
At the start of the main file is the comment:
; ==============================================================================In the build area there is the main hex firmware and then three configurations with the following contents:
; firmware/v1.0/compiled/config-1.75mhz.hexWe can see these differing in the values after 0500000. The next two bytes (0101) map to serial and parallel interface being enabled. These define how the AY-3-8912 registers can be accessed, either using the original deviceās parallel data bus or via a newer serial link. The serial link can be used to send register-value pairs to the device rather than use a real AY compatible parallel bus interface.
Then there is a differing byte (7A, 78, or 6B respectively) which is pulled into the timer 0 frequency code and used to set OCR0A in the previous code.
Finally that last byte of the configuration (3A) relating to USART baud, which I infer from older comments in the README file will be 57600, but this is as yet unverified.
On studying the code, it quickly becomes apparent that the whole execution is optimised for specific MCU clock frequencies. This is particularly notable in the interrupt routines, for example, the following:
; ==============================================================================Here we can see that running at 20MHz (for example) violates the timing constraint to respond with the data on the bus. Running at 24MHz, 25MHz and 27MHz appears to be fine. There are a number of other places in the code where similar comments have been made.
The conclusion seems pretty clear. A standard Arduino Uno or Nano running at 16MHz would not work. Something at 20MHz might do the job with some limits, but there is definitely a reason the board is using 27MHz.
There is a key issue however. AVR 8-bit microcontrollers are typically only specified for up to 20MHz operation. Iāve certainly not found any ATMega48 through to ATMega328 that has a higher frequency specification. There are some newer 8-bit devices that might stretch to 24MHz.
But Iām now wondering if the MCU is being overclocked on this board. It would appear, according to some superficial searching, that people have been overclocking AVRs for yearsā¦
Timer Configuration and PWM Output
The emulator is using PWM to produce audio from the AVR. The PWM channels/timers are allocated as follows:
AVR PinTimer OutputCompare RegisterTimerSystem ClockD4 / PD4N/AOCR0A0Channel AD9 / PB1OC1AOCR1AL1Channel BD11 / PB3OC2AOCR2A2Channel CD10 / PB2OC1BOCR1BL1The first timer, Timer 0, Iāve already mentioned, is used to set the basic internal system āclockā for the emulation. In the real AY PSG the internal clock for tones is set to the external clock / 16 and for envelopes is external clock / 256. In the emulation this is all set in code and the CLOCK input is ignored.
The 8-bit Timer 0 configuration is as follows:
This uses timer 0 in Fast PWM mode (WGM = 7) with TOP = OCR0A and no prescaler. There is a check in the main loop for Timer 0 overflow which is then used to determine if the sound generation should be processed. This effectively sets the CLOCK for the emulation. The AY CLOCK input is meant to be between 1MHz and 2MHz and EEPROM configurations are provided to emulate 1.75MH, 1.78MHz and 2.0MHz external clocks.
In Fast PWM mode, from the ATMega328 datasheet, for Timer 0, the frequency is given by:
Where N is the prescaler factor, so in this case 1. But this appears to be stated for the case when TOP = 255. If the TOP is reduced, so when TOP = OC0A, then presumably that 256 should be (TOP + 1). Assuming this to be the case, then with a 27MHz clock and the previously mentioned values from the EEPROM, we have
These give a basic operating frequency of between 3.5MHz and 4MHz which is twice as fast as the real PSG. Iām guessing that this is because the sound generation code (later) toggles the output value on each period, which therefore requires doubling the frequency to generate the high and low periods.
Note that although this timer is configured in Fast PWM mode, it isnāt actually running PWM, it is just used as a timer. The timer also never ātriggersā as such ā it is polled for overflow within the main code loop.
The 16-bit Timer 1 configuration:
This uses timer 1 in 8-bit Fast PWM mode (WGM = 5) with TOP = 0xFF. There is no pre-scaling and OC1A/OC1B cleared on compare match with OC1A/OC1B set at BOTTOM (non-inverting mode).
The 8-bit Timer 2 configuration:
This uses timer 2 in Fast PWM module with TOP = 0xFF (WGM = 3). OC2 is clear on match and set at BOTTOM (non-inverting again).
The PWM resolution for both Timer 1 and Timer 2 will be 8-bits (0 to 255) and the frequency for the output is given by the same formula used for Timer 0, giving a PWM frequency of:
Bus Access
There is a comprehensive bus access protocol defined in the AY-3-8910/12 datasheet with several possible modes involving the control signals BC1, BC2, BDIR, and A8 plus /A9 (in the case of the 8910). In particular, there is some redundancy in how the āLATCHā is indicated (see section 2.3 in the āAY-3-8910/8912 Programmable Sound Generator Data Manualā ā more here: AY-3-8910 Experimenter PCB Design).
For the emulator, BC1 is tied into the AVR INT0 (via PD2/D2) and BDIR is tied into AVR INT1 (via PD3/D3). If the serial interface is used then there is also an interrupt for the UART. BC2 is ignored so all responses are enacted upon as if BC2 is set to HIGH.:
The basic operation, as far as I can see, is as follows:
INT0 ISR - triggered on BC1 -> 1There is a pseudo image of all AY registers stored in RAM which is used by the main loop for the sound processing. This RAM image is updated when the AY is written to and can be accessed when the AY is read.
Note that there is no access control. If an interrupt comes in part way through an update to the sound generators they will stop process and then continue from that point unaware than any register updates have taken place. This does mean that if any registers are accessed twice, it is quite possible that they would have changed by the time of the second access.
Similar logic happens within the UART interrupt handler, but instead address and data values are obtained over the serial port and interactions with RAM updated according to the bytes recieved.
Iāve not looked further into the serial handling at this time other than to note that all updating is performed withing the UART ISR which is receive only.
Main Sound Processing Loop
The main logic free runs as follows:
MAIN Loop:So the loop essentially pauses until timer 0 overflows at which point all sound generation activity undertakes a single scan and then the PWM sound generation registers are updated.
Before I dive in, I should note that the register definitions are of the form AY_REGnn where nn is a decimal from 00 to 15. The datasheet describes Ro where o is an octal value from R0 to R7, then R10 to R17. I will be using the decimal versions here to match with the code.
Iām not going to work through how the sound generation works in its entirety right now, but I will just include a note about the tone generation. Here is the code for channel A.
; Channel AAll counters (CntAL and CntAH for channel A) are 16-bit values. AY_REG00 and AY_REG01 are the RAM copies of the two tone generator registers for channel A.
We can see that the channel counter is decremented on each scan through the routine implementing the following pseudo code:
counter--This means that the output square wave value for channel A will toggle between HIGH and LOW every time the counter reaches zero and that the counter will have to count to zero twice to make a complete cycle of the square wave.
The datasheet states that the tone registers define a 12-bit tone generator period:
The resulting sound frequency is given by the equation:
As we have to count twice to get our square wave output, we can see why the timer 0 āclockā frequency has to be twice the desired running CLOCK of the AY-3-8912. An alternative implementation could have been to add an additional check as part of the countdown to change the waveform half-way through.
This does mean that all sound generator registers are processed twice as quickly as expected so that might have to be taken into account when calculating other parameters.
The main impact would be for the envelope generator, which according to the data sheet runs a frequency CLOCK / 256. There is a EG period counter defined by AY_REG11 and AY_REG12 (R13 and R14) for further subdivision, so a full sweep of the envelope will happen with a frequency of CLOCK / (256 * EGcounter).
The datasheet also notes that āthe envelope generator further counts down the envelope frequency by 16 producing a 16-state per cycle envelope patternā. This means that the frequency required to process each individual step of these 16 states is: 16 * CLOCK / (256 * EGCounter) or CLOCK / (16 * EGCounter).
The Envelope Code is essentially doing the following:
Every LOOP scan:This implies that a full sweep of the envelope takes EGcounter * 32 scans of the main LOOP. As the LOOP is running at twice the frequency of the CLOCK. this gives an EG frequency of:
Which matches the datasheet. So the doubling of the LOOP frequency is taken into account by having 32 steps for the EG base period rather than 16.
A few other observations from the code:
Curiously there are two envelope volume tables provided as options. The first (āAY_TABLEā) distinctly shows the doubling of levels turning 16 values into 32 values. The second (āYM_TABLEā) appears to have some interpolation between values giving a higher resolution envelope.
From wikipedia: āThe input clock is first divided by 16 (or by 8 in the YM2149, because the envelope generator has twice as many steps, and thus needs twice as many clocks to complete a full cycle), and then by the 16-bit value.ā
So by starting with double the CLOCK frequency, we effectively get YM compatibility āfor freeā.
Only a single envelope table is required ā it defines a linear incrementing pattern that is then used and reused in various ways according to the EG control bits in AY_REG13 (R15) as per figure 7 in the datasheet. Iām not going to dig into that further at this point. I might come back to it in the future.
Iām also not going to dig into the noise generation, mixer or amplitude control at this time.
Closing Thoughts
I really like I feel I know a lot more about how the AY-3-8910/8912 work now and certainly am, as usual, in awe of those who figured all this out and then how to emulate it on a modern (ish) microcontroller.
It is also interesting to note that the emulation hasnāt been updated, as far as I know, for anything more capable than an 8-bit AVR. I guessing it just isnāt necessary and avoiding the whole 3V3/5V logic thing has a certain appeal.
The two commercially available solutions Iāve seen from RC2014 for the WhyEm sound card and the vRetro 28-pin direct replacements, stick with AVR and overclock as far as I can tell. RC2014 using ATMega48AP at 27MHz and vRetro using two ATTiny MCUs and what I think is a 30MHz oscillator.
I would like to see if I can get a standard ATMega328P running the code and then Iād be really interested in seeing if it could be made to run on a Logic Green LGT8F328 āAVR cloneā that apparently should be able to run at 32MHz.
I believe Iāve convinced myself not to attempt to build the AY-3-8910 out of discrete logicā¦
Kevin
#arduino #atmega328 #avr #ay38910 #ay38912 #vretroNote to self:
"I do not need to build an AY-3-8910 out of discrete logic chips."
"I do not need to build an AY-3-8910 out of discrete logic chips."
"I do not need to build..."
https://github.com/mengstr/Discrete-AY-3-8910
But how cool would that be!