Showing posts with label AVR. Show all posts
Showing posts with label AVR. Show all posts

Sunday, 22 November 2026

AVR C vs Assembler, a Real World Example

This from the Patreon archive, part of a project I was working on (and still haven't finished).

I am working on a project for an ATmega microcontroller, which is currently written in C using avr-gcc to compile it.

Building C with AVR_GCC

For reference, this is my three line build script. It allows me to have a clean and simple build environment with just a batch file to build the file, rather that the behemoth of whatever the current flavour of the month Atmel development platform is.:

The first line is the C compiler, this generates a binary output.

avr-gcc -Wall -g -Os -mmcu=atmega1284p -DF_CPU=8000000
 -o Test.bin Test.c Utils.c

The second line generate a hex file, suitable for programming the microcontroller with avrdude

avr-objcopy -j .text -j .data -O ihex Test.bin Test.hex

The final line is optional, and generates a listing file which will show the combined C and AVR assembler source.

avr-objdump -h -S Test.bin > Test.lss

C is great for the general structure of the code, the user interface and anything not speed-critical. I am looking to add some new functionality which requires precise timing.

I thought it would be interesting to see if it was possible to write some suitable C that would be complied down to reasonable assembler.

The Task

The task in hand is to generate a 1MHz clock whilst also incrementing at address bus during the low part of the clock cycle.

The microcontroller is running at 8MHz, that means I have 8 cycles to complete each address.

The AVR is a RISC processor, much like the 6502, with a small number of fast, simple instructions, in contrast to things like the PIC and the Z80, with large numbers of slower but more capable instructions.

In the AVR many of the instructions are single cycle, so I could have up to 8 instructions in the loop.

The pseudo-code would look something like this:

loop:
    set clock low (address bus not valid)
    update address bus
    set clock high (address bus should contain valid data)
    goto loop

The target read and write cycles use the period when the clock is low to change the address bus. The time when the clock is high, the bus should remain unchanged. Once the clock goes low again, it can be modified.

First Attempt

The shortest way to write this in C turned out to be the worst way to write it in assembler.

This is using direct modifications to the ports, which should be faster, right?

It seemed like using PORTC++ to increment the value of the output port would be the fastest option.

Nope.

That turned into three cycles of "read the port into a temporary register, increment that register, write it back out to the port". Then some poor optimisation, reading it straight back in again to check if it was zero.

The clock high and low instructions are using SBI (Set Bit on Io register) and CBI (Clear Bit on Io register), single instructions, which is neat, but these are two cycles, so it will be better if I use the single cycle OUT instruction to write a pre-calculated value.

Second Attempt

OK, it should never need to read from the port, so lets setup two local 8-bit registers to hold the address bus value. I have used "address" for the lower byte and "page" for the upper byte.

This time it is better. As before, it has chosen to implement address++ as "subtract 255 from address" rather than "add 1 to address", both give the same results and take the same time but I guess there are reasons.

I worked that out as 9 cycles, the OUT (OUTput) and SUBI (SUBtract Immediate) instructions are single cycle, RJMP (Relative JuMP) is two cycles and BRNE (BRanch if Not Equal) is two cycles if true, one if false (making that if statement two cycles whichever path is taken).

Testing that out on the real hardware and it is working, but it is indeed 9 cycles, the clock output (top) being 894kHz rather than 1MHz as it should be (middle trace).

Switching the middle trace to address line A0, you can see the it is changing whilst the clock is low, as it should.

It is important to note that the compiler output is not guaranteed to stay the same, I have seen code changes elsewhere in the project affect routines that were unrelated and previously working. Sometimes another routine requires some resource which means the unrelated code now has to do something in a different way.

I wouldn't want to rely on this code remaining that way, so I think I will write this in assembler.

Assembler Version

I was able to get it down to 8 cycles in assembler, by using the ADIW instruction (ADd Immediate to Word). Contrary to what it says in the datasheet (!), this is a two cycle instruction which adds a value to a 16-bit number stored in two adjacent registers, in this case r26 and r27.

That is 8 cycles, as you can see, clocking in at 1.004MHz, but it works out asymmetric unfortunately.

The clock set instructions are single cycle, so I have clock set (one cycle), three available cycles, clock set (one cycle), three more available cycles. 

That gives two three cycle gaps. In those gaps, I have three two-cycle tasks to perform, incrementing the address, updating the IO ports and jumping back to the start of the loop.

I could split the port update, but I think it is better to have it slightly asymmetric rather that splitting the port writes and changing part of the address whilst the clock is high.

Worse Case

I thought I would have a go at a very unlikely to succeed approach, just to see how bad it could be.

Here I will use a 16 bit word to store the address, and to split it into high and low bytes to write it out.

Under the hood, there are lots of ways that could be implemented. In a natively 8-bit system, the 16-bit value would be stored as two bytes, but that is difficult to write in C. 

(this is sort of what C UNIONs were designed for a, a word and an array of two bytes sharing the same space, but that seemed like it would over-complicate things)

One way to so this would be to use something like

port_address_high = (address >> 8);
port_address_low = (address & $00FF);

A clever compiler might spot this and be able to optimise that into direct byte accesses, but it might actually have to implement the shift and mask operations, depending on how it is written. The 16-bit addition could also end up very complicated, depending on implementation.

Well, it turns out it is a clever compiler.

I was going to use this as a demonstration of a worst case, but it is actually pretty decent.

Here it is using two one-cycle operations to increment the address. Both subtract!

As hoped, it has bypassed the shift and mask operations to use the underlying two bytes.

That is actually 8 cycles, pretty good for some code that was intended to be awful.

The Final Version

One interesting thing about that version is the address++ is implemented as two instructions, SUBI (SUBtract Immediate from register) and SBCI (SuBtract with Carry Immediate ).

That is using the carry flag from the first operation to nullify the second operation. Most of the time, carry will be set as $FF is larger than the value in the register. The second instruction is then:

register = register - $FF - 1

which is the same as

register = register - 0

When there is no carry from the first operation, the second becomes

register = register - $FF - 0

or rather

register = register + 1

Neat.

It is also interesting to note that the carry flag is not affected by the OUT instruction.

Can you see where I am going here?

You could put an OUT instruction in between those without affecting their operation.

This is my final version, the SUBI and SBCI have been placed either side of the OUT instruction, creating a balanced four cycles each side symmetric clock waveform.

Let's see how it does, with the host 1MHz clock on the middle trace for reference.

Before, it was asymmetric, with 375ns high and 625ns low.

And now it is symmetric, 500ns high, 500ns low. Perfect.

That will do nicely.


(yes, I am still using that caption from the previous post)

I still have most of the things I make in stock, and can ship worldwide.

The easiest way these days is to contact me using the link at the top of the page. Tell me what you want to order and your address so I can get a quote for shipping and duties etc.

The new Minstrel 3 with keyboard are £150 kit, £190 built (£250 kit with Minstrel ZXpand II, £300 built).

Also a short run of Mini PET 40/80s with keyboard, with a few updates. Order now, and you will get one of the new ones in a couple of weeks. £450 kit / £500 built.

The Mini PET 40/80 internal PET replacement boards are also available now, £350 kit / £375 built.


Patreon

If you enjoy posts like this, you can support me via Patreon, and get access to advance previews of blog posts, and exclusive posts.

You also get progress updates on new projects and other behind the scenes updates, as well as access to my Patreon only Discord server for even more regular updates, and to discuss your own projects.

Sunday, 22 February 2026

AVR Command Line Hello World in C

I have planned to write this sort of post several times, but for whatever reason it has never worked out. I would take all the screenshots and code saves etc. and by the time I came to write it all up, I would have lost them, or forgot what I took them for.

This time I wrote it up as I was going, so I finally get to complete it.


I have found I don't get along with the many and varied development environments and frameworks and plugins etc. And have ranted about them at nauseam in the past.

A lot of the time, I just want something nice an simple. Hello World, a flashing LED etc. and it's not always easy to get that without hundreds even thousands of lines of irrelevant code being added to your project.

Here I present the minimalistic approach I take when I want, what I consider, the easy approach. (I appreciate that my idea of "easy" and "painless" is very different to others, but this is what works for me)

I am going back to plain text files and command line compiles, and a simple flashing LED.

Development Board

I am using the AVR64DD32 Curiosity Nano board. This is one of many of this type of board, a microcontroller with it's pins connected to two rows of 0.1" spaced pads, and an integrated programmer / debugger at the end, all powered from a USB connector (microUSB on the older boards, USB C on the newer ones).

You can use these in various ways, in the full development environment there are powerful in system debugging and monitoring, but today I am going to use what they call "drag and drop" programming.

When you plug in the Curiosity Nano, it appears as a composite USB device with many features, including USB serial and a USB storage device.

When you open that drive, you see a few files, mostly information about that board and links to the product page which contains links to example projects on github.

The status.txt files is magically generated and shows info about the current settings. It works the other way, if you copy a .hex file into that folder, it programs that into the device. Very neat.

The .hex files are cached in the file views, although it doesn't really exist, you can't read the .hex file back. But you can overwrite it with a new version as you go.

If you unplug the device and plug it back in, any hex files will disappear as they were never really there.

Occasionally I get an error saying "Read Only Filing System", but that resolves by unplugging and plugging back in. (I think it happens when I am too quick with copying a new version on there)

Writing the Code

Now all I need to do is generate a .hex file.

I will start with a nice simple flashing LED, written in C.

The development board has an LED wired to pin PF5.

// Blinking LED
      
#define F_CPU 4000000UL
#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
    PORTF_DIR = (1<<5);

    while(1)
    {
        PORTF_OUTTGL = (1<<5);
        _delay_ms(500);
    }
}

That is about as minimal as you can get.

Building

I am going to make a bash script to build this (you can do a makefile if you find that easier)

I first create a build directory to hold the output files away from the source.

mkdir build

At the start of the build script, I change into that folder and then clear any temporary files.

cd build
rm *.o -f
rm *.d -f
rm test.* -f

With older chips, support was built into avr-gcc, so the command line would be something like

avr-gcc -Wall -g -Os -mmcu=atmega1284p -o LEDTest.bin LEDtest.c

However, the newer AVR chips are not included, so you need to reference library files. You can install these packs separately, but if you have MPlabX installed, they are already there.

I found the easiest way to get the appropriate build lines is to copy bits from the build output of one of the development environments. Setup a simple project with just a main.c and look at the build output.

The line I took was as follows. This will vary based on system, paths, versions etc. so don't expect this to work on your system.

/usr/bin/avr-gcc -mmcu=avr64dd32 -I "/opt/microchip/mplabx/v6.25/packs/Microchip/AVR-Dx_DFP/2.7.321/include" -B "/opt/microchip/mplabx/v6.25/packs/Microchip/AVR-Dx_DFP/2.7.321/gcc/dev/avr64dd32" -x c -c -D__AVR64DD32__ -funsigned-char -funsigned-bitfields -O1 -ffunction-sections -fdata-sections -fpack-struct -fshort-enums -Wall -MD -MP -MF main.o.d -MT main.o.d -MT main.o -o main.o ../main.c -DXPRJ_default=default

(ah, it used to be so much simpler in the olden days says the old man yelling at clouds...... I should have that gif on speeddial, ah but then the youth of today probably don't know what speeddial was...... insert second copy of old man yells at clouds gif)

There is a lot going on, I tidied it slightly by having all the object files in the current directory and using ../main.c for the single reference to the source file.

The next step is to link it

/usr/bin/avr-gcc  -mmcu=avr64dd32 -B "/opt/microchip/mplabx/v6.25/packs/Microchip/AVR-Dx_DFP/2.7.321/gcc/dev/avr64dd32"  -D__AVR64DD32__  -Wl,-Map="hello.map" -o hello.elf main.o  -DXPRJ_default=default    -Wl,--defsym=__MPLAB_BUILD=1 -Wl,--gc-sections -Wl,--start-group  -Wl,-lm -Wl,--end-group

Again, taken from the build output with the paths tidied up. I am not sure how many of those options are actually necessary, but I have left them all in for the moment. Maybe one day I will look at streamlining that?

That generates an .elf file. The final step is to convert the .elf file into the .hex file we need.

/usr/bin/avr-objcopy -O ihex hello.elf hello.hex

And an optional step generates a listing file.

/usr/bin/avr-objdump -h -S hello.elf > hello.lss

I Finally clean up the build files I don't need to keep, the full script is as follows:

#!/bin/bash
cd build
rm *.o -f 
rm *.d -f 
rm hello.* -f
      
/usr/bin/avr-gcc -mmcu=avr64dd32 -I
"/opt/microchip/mplabx/v6.25/packs/Microchip/AVR-Dx_DFP/2.7.321/include"
-B "/opt/microchip/mplabx/v6.25/packs/Microchip/AVR-Dx_DFP/2.7.321/gcc/dev/avr64dd32" 
-x c -c -D__AVR64DD32__; -funsigned-char -funsigned-bitfields -O1
-ffunction-sections -fdata-sections -fpack-struct -fshort-enums -Wall -MD
-MP -MF main.o.d -MT main.o.d -MT main.o -o main.o ../main.c
-DXPRJ_default=default 

/usr/bin/avr-gcc -mmcu=avr64dd32 -B
"/opt/microchip/mplabx/v6.25/packs/Microchip/AVR-Dx_DFP/2.7.321/gcc/dev/avr64dd32"
-D__AVR64DD32__ -Wl,-Map="hello.map" -o hello.elf main.o
-DXPRJ_default=default -Wl,--defsym=__MPLAB_BUILD=1
-Wl,--gc-sections -Wl,--start-group -Wl,-lm -Wl,--end-group
      
/usr/bin/avr-objcopy -O ihex hello.elf hello.hex 
/usr/bin/avr-objdump -h -S hello.elf > hello.lss 

rm *.o -f 
rm *.d -f

The build.sh file is saved and and made it executable with

chmod +x build.sh

Now I just run ./build.sh and hopefully get no errors.

./build.sh

Then just copy the .hex file to the mounted folder to program it. Your paths will vary unless your username is also Dave. Hello Dave.

cp build/hello.hex /media/dave/CURIOSITY/

All being well, the LED will start flashing away at about 1 Hz.

Checking your work.

You can double check with a logic analyser. The Curiosity Nano comes with a set of pin headers, I don't know what they get up to locked in those red boxes, but they always seem to be stuck together and a little difficult to separate without breaking them.

The holes in the PCB are a little offset, which is a neat feature. That holds the pins in place without soldering. Handy for some quick testing, but I would still solder for anything permanent.

And there we have a square wave, approximately 500ms high, 500ms low. It is slightly longer due to the time taken to toggle the LED and jump back to the start of the loop.

That was a trivial exercise, but a useful one to get started.

Sometimes you just need a sanity check. Can I still get the LED to flash? OK, so the code is actually being updated and is running.

Adding More Functionality

Now it is over to you to add in your code.

If you are just doing "if this input, then do that output" etc., away you go. If you need timers or ADCs or glue logic or events or whatever, you will need to set those up.

Depending on what you are doing, it is sometimes easier to read the datasheet and work out which registers you need to setup for your application. It is often only a few.

But getting started, it can be easier to use things like Atmel Start or MCC Melody (or whatever the next flavour of the month is).

You can use those to create a dummy project and generate a load of code, and then pick and choose the bits you need to add to your simple code.

Atmel Start

I generally prefer Atmel Start as that has a web front end, so you don't need to install or update anything, although unfortunately it has stopped being updated itself. It support things up to the AVR DA and DB series, but has not been updated to include the DD or Ex series for example.

It has a graphical view for linking things together which is helpful for clocks and lookup tables and events.

The code it generates it a good starting point. Commented out code for bits you don't need to change (most registers default to 0 at power on, so no point in overwriting 0 with 0.

Take the bits you need to change, they show all the defines and most of them have comments.

MCC Melody

The current version is MCC Melody in MPlabX. This is a Java based platform which I always struggle with. It seems to be the user interface is somehow fragile, and it locks up too easily. Like it is a picture of a user interface that checks for mouse clicks when it feels like it.

The code these generate does not use defines, just gives you the calculated value. e.g.

Some modules have the option to comment out the = 0 lines, but not all do, so by default you get a load of unnecessary code.

I am also not a fan of they way they remove the leading zeroes. Instead of 0x00 they use 0x0, which just looks wrong to me. The same with 16 bit numbers, 0x02ff is written as 0x2ff.

However you choose to generate it, you can add the bits you need to your code.

Most of these peripherals do their own thing, so once you have them setup the processor is free to do other things, so I often just leave it looping around flashing the LED. It's reassuring to see the heartbeat. I also occasionally change the period of the timer to make sure it has been updated.

A Bit of Assembler?

I was going to stick with C for this, but there is one bit which always needs assembler.

Unlike previous Atmel chips, where the clock settings are programmed fuses, the Microchip chips always start with the internal oscillator enabled. That can be quite useful if you accidentally set the fuses to use an external crystal and you don't have one connected (ask me how I know).

The default clock on these devices is 24MHz, with a divide by 6 to get 4MHz.

There is a line at the start of the main.c file is used to tell the delay function about that so it know how many cycles it will need to waste to get to the required 500ms.

#define F_CPU 4000000UL

In order to change that, you need to write to a register, however it is not as easy as a simple assignment as that register is protected, so you need a wrapper function to unlock it first.

The register is only unlocked for a few cycles, so this need to be written in assembler as C compilers have a habit of moving things around to optimise the code, so the order of instructions can change.

I am surprised this is not a library function, like _delay_ms as used above, but it does not seem to be.

The code generated by both Atmel Start and Microchip MCC has a lot going on to deal with lots of different conditionals and various macros to deal with formatting it as a C callable assembler function.

I usually distil that down to a much simpler function.

#include <avr/io.h>

.global		protected_write_io
.section	.text_protected_write_io, "ax", @progbits
.type		protected_write_io, @function

protected_write_io :
	movw    r30, r24                // Load addr into Z
	out     CCP, r22                // Start CCP handshake
	st      Z, r20                  // Write value to I/O register
	ret                             // Return to caller

.size		protected_write_io, . - protected_write_io

What it is doing is setting the Z register to the address of the register to be written (Z is a 16 bit register made out of two 8 bit registers, r30 and r31).

Once the Z register is preloaded with the address at r24 and r25, the magic unlock code is written to the CCP (Code Configuration Protection) port. That unlocks the protected registers for a few cycles and then the value in r20 is written to the register pointed to be Z.

The registers are sort of like the zero page in a 6502, so in this case ST Z, r20 is a bit like a zero page indirect LDA, r20 STA (r30,X).

That does mean I have a separate protected_io.s file and also a header file with the function definition for the generic function, and a second function wrapper for the more specific version. Which is not ideal, it just means extra files and some extra lines in the build script.

extern void protected_write_io(void *addr, uint8_t magic, uint8_t value);

static inline void ccp_write_io(void *addr, uint8_t value)
{
	protected_write_io(addr, CCP_IOREG_gc, value);
}

Then you just need the actual call in your code to change the value to 16MHz or 24MHz etc as required.

ccp_write_io((void *)&(CLKCTRL.OSCHFCTRLA), CLKCTRL_FRQSEL_24M_gc);

N.B. watch out for CLKCTRL_FRQSEL_24M_gc, it seems to be CLKCTRL_FREQSEL_24M_gc in the code generated by Atmel Start but the current libraries seem to have lost the E in FREQ.

Inline Assembler

I have been meaning to look at rewriting that with inline assembly. This seems to be a good time.

static void ccp_write_io(void *addr, uint8_t value)
{
    uint8_t magic = CCP_IOREG_gc;
    asm volatile (
        "out %0, %1 \n\t"
        "st %a2, %3 \n\t"
        : 
        : "I" (_SFR_IO_ADDR(CCP)), "r" (magic), "z" (addr), "r" (value)
    );
}

I have made it a single function. It took me a while to work out the best way to use the inline assembler syntax. It's a little convoluted, but you write the assembly in a similar style to printf statements, with %0 etc. placeholders for variables.

I would point you at the official documentation, but for some reason all the code on that page is missing

See this version instead which still has the code intact.

The four parameters are passed as %0 through to %3, and those refer to the items that appear after the colon (the values after the string in a printf statement). The first section is for return values, in this case empty. The second is for parameters. There is also a third for any registers you need to tell the compiler that you have used, which I am not using here as I am only using the ones already in the parameter list.

The type is in quotes, "I" is a 6-bit positive integer constant (as is required by the out statement). "r" is a register, so this means that the variable magic is copied into a register, and the name of that register is inserted into the code in place of the %1. The compiler chooses an appropriate register for you.

"z" tells the compiler not to choose one, and forces it to use the Z register (r30 and r31 as previously mention). %2 would have been replaced with the name of the first register, r30, but %a2 gives the Z as required for the st Z.

Looking at the code which is generated (in the .lss file)

ldi r24, 0xD8
ldi r25, 0x24
ldi r30, 0x68
ldi r31, 0x00
out 0x34, r24
st Z, r25

The first four lines are loading the registers and then the last two lines are the unlock and the register write.

That is a few lines shorter than the one generated by the code in the separate file as the parameters are passed in different registers and have to be copied into r30 and r31. Here I can specify the values are placed directly into the registers I need to save the unnecessary step.

You can of course just cut and paste the code above rather than having to understand it. That is what I intend to do next time.

If you upload that now, the LED will flash faster as the clock is now running faster.

In order to get it back to the correct time, you also need to change the #define F_CPU the at the start.

#define F_CPU 24000000UL

Rebuild and re-copy and it should be back to 1Hz.

(this is a slightly earlier version where I hard coded the CCP port before I worked out how to pass that properly, and also went for 16MHz rather than 24MHz)

More Assembler

This next section also goes into the assembler weeds a bit, but I think it is important to see how seemingly insignificant changes to the C code can make big differences to the size and speed of the assembly generated.

Normally when you use the code builders or something like the Arduino, you get nice wrapper functions, e.g.

LED_Toggle();

That isolates you from a lot of the underlying implementation, which in many cases is what you want.

In the early days of Arduino, I remember the IO instructions used to generate a load a code, I think they are a bit more streamlined these days.

The AVR ones usually map down to single instructions, in this case wrapped in a do-while loop to avoid compiler optimisation.

#define LED_Toggle() do { PORTF_OUTTGL = 0x20; } while(0)

You can duplicate things like that if you find it helpful, but all you need is the important bit.

PORTF_OUTTGL = (1<<5);

I have used (1<<5) as it is pin PF5, but the autogenerated code just goes for 0x20. Up to you, you could also use %0010000, or 32 (or even 040 if you are perverse). Whatever works for you, they all compile down to the same thing.

ldi r24, 0x20
sts 0x04A7, r24

Some of the code uses a dot rather than an underscore. They are pretty much interchangeable, but subtly different in the code which is generated.

PORTF.OUTTGL = (1<<5);

This generates a less efficient implementation using a redirector. That can be more efficient if you are running a series of this sort of instruction, but is worse by a few lines for a one off.

ldi r30, 0xA0
ldi r31, 0x04
ldi r24, 0x20
std Z+7, r24

With some registers, you can also access shortcut "virtual ports" which produce even more efficient code.

VPORTF_DIR = (1<<5);

The code is 1 word and 1 cycle shorter. That can make a difference when you are doing low level pin toggling. Especially if you preload registers with the things you want to write, you IO calls can come down to a single cycle out instruction.

ldi r24, 0x20
out 0x14, r24

If that isn't enough, you can also use the "set" and "clear" versions which will only change certain bits. Useful if you want to turn on one output without knowing what the rest are set as, or having to do a ready, modify, write sequence.

So

PORTF_DIR |= (1<<5)

Could be replaced with the more efficient version.

PORTF_DIRSET = (1<<5);

One of the purposes of a simple test build like this is you can try out the different options in isolation, and test them out and also look at the code generated. (well, I say simple, I suppose I should prefix that with "relatively")

How did it go?

In this case, I had been using the MCC generated code as a starting point, but it just wasn't working. Going back to the minimal code and adding a few lines to set the appropriate registers, I was able to see the correct code was being generated and nothing else was interfering with it. That actually turned out to be a silicon bug in the chip I was using, and when I changed to a different one, it started working as designed.

There was a longer, rantier version of that conclusion in the original version of this on Patreon as I had wasted a lot of time on that and another problem, but I will keep things civil on here.


Adverts

My Tindie store contains all sort of kits, test gear and upgrades for the ZX80, ZX81, Jupiter ACE, and Commodore PET.


Patreon

You can support me via Patreon, and get access to advance previews of blog posts, and progress updates on new projects like the Mini PET II and Mini VIC and other behind the scenes updates. This also includes access to my Patreon only Discord server for even more regular updates.

Sunday, 25 January 2026

A New CRTC for the Minstrel 4th? Part 3

The final part (so far) of the development of the replacement CRTC microcontroller for the Minstrel 4th.

To recap, the microcontroller which generates the video sync and steps through the video RAM (the CRTC) on the Minstrel 4th was announced as being discontinued, so I have redesigned it to work on a different microcontroller.

In the previous post, the new code on the new microcontroller was running, but it was running on a curiosity nano development board, wired up to a Minstrel 4th.

Just to be sure, I wanted to try running with just the microcontroller. The development board has an

AVR64EA48 = AVR architecture, 64K program space, E series, A variant, 48 pins

For the final version, I am planning to use

AVR16EA28 = AVR architecture, 16K program space, E series, A variant, 28 pins

Those were not it stock at the time, so I went for

AVR64EA28 = AVR architecture, 64K program space, E series, A variant, 28 pins

The development board has a handy feature where it acts as a USB storage device, so you can program it by copying a hex file to the device, which was neat, and I could do it from the command line.

I don't think I can use that for production programming, I need to check if I can use that mechanism to set all the flags and fuses I need.

To program those, I use the jig I originally made for the Minstrel 4D (where I used an AVR DA series chip for the SD card interface). That uses another of the Curiosity Nano boards, disconnected from it's onboard chip and wired to a ZIF socket to work as a programmer.

I looked all around the new MPLAB X environment, but couldn't find the equivalent of this page from the old Atmel Studio, so I have gone back to that.

That lets me connect to the IC in the ZIF socket and program it.

My plan had been to make a little plug in PCB, like the clock board for the Mini VIC.

But when I looked at the wiring, it was clear the lines were crisscrossing all over the place, so it would have been quite a mess.

I decided to go for a quicker solution, and moved it to a little breadboard and proceeded to wire it into the Minstrel 4th.

The breadboard approach will do for this testing, I will hopefully be ordering new PCBs soon.

I plug the jumper wires into a extra socket, so I can detach them, or move them to a different board etc.

Let's give it a go.

A perfectly square bit of black dirt in the middle of the screen?

Oh no, it's the cursor, but what's it doing in the middle?

Hmm, no, that's definitely not right.

Is the ROM messed up? Let's try a different one.

I mean it's wrong, but it's not very wrong.....

Let's try FOR N=1 TO 22 PRINT N NEXT N (lazy programmer again, NEXT is on the N key, I've been doing that for 45 years.....)

Hmm, it started well....

Ah, OK, I see what's happened, two of the address lines in the row counter have got mixed up.

Give me a second.

That's better.

More testing

Ooops, I left the 2x ZX81 speed ROM in, and now the mummies on Tut-Tut are moving sooooo fast.

Perilous Swamp is now my go-to test for scrolling problems, but that seems OK, even if I did get eaten by a Gorgon.

Maybe I shouldn't have ran around singing "Gorgon is a moron, Gorgon is a moron"...

Hmm, I still don't think I can put it into production like that.

Time to re-route the PCB.

Ouch that looks like it's going to be fun.

I put that off for a while and got on with some other stuff.

Roll onto 2026.

Adapter Board

I decided I should test this further, so rather than redoing the whole board, I made a small adapter board.

This is designed to fit in the ATmega48PA socket and wire the signals up to the AVR16EA28.

I had to add a couple of extra sockets to the stack to clear the video connector.

The AVR16EA28's were back in stock now, so I ordered some of those.

I rebuilt the code for that chip and programmed it.

I am currently moving a lot of things around the workshop, so I only have a small bench space available. I have been managing quite well using a small LCD monitor.

Time to clear away the Mini PET and test this out.

That all looks good.

Even on the small LCD.

There you go, the compulsory VLIST, and now the 10 PRINT.

Now comes the tricky part.

I have proved I _CAN_ do it, but I am not sure if I _SHOULD_ do it?

I have various other changes I would like to make the the Minstrel 4th board if I were to respin it, and those are only designs so far, I need to prototype them up.

The ATmega48PA is also still in stock, and I have bought a few tubes just in case.

I think for the moment I will keep with the original "working quite all right thank you very much, until they said it was discontinued and then don't seem to have actually go through with discontinuing it" microcontroller.

That might all have been an unnecessary journey, but at least I learned a few things along the way.


Adverts

Check out my Tindie store for all sort of kits, test gear and upgrades for the ZX80, ZX81, Jupiter ACE, Commodore PET.


Patreon

You can support me via Patreon, and get access to advance previews of development logs like the ones these posts are based on, and progress on new projects like the Mini PET II and Mini VIC and other behind the scenes updates. Mini PET II Parts 13 and 14 are part written, I just need to do some prototyping and get some screencaps to complete part 13 and then decided if part 14's plan is even possible. This also includes access to my Patreon only Discord server for even more regular updates.