
Sign up to save your podcasts
Or


Survey 2023 Results. Dan’s MEGA65 Digest for September 2023.
The MEGA65 Community Survey 2023 is now complete! It opened on August 14, ran for three weeks, and received 509 submissions. A HUGE thank you to everyone who submitted!
Let’s do a quick update, then onto the results!
We do not yet have a formal release candidate for the upcoming v0.96 release, which is intended to be the factory installed release for the next delivery batch. We are still waiting on test hardware for the revision 5 main board to arrive. Once it does, we will clean up the changes and document a formal test process that you can try on your own computer.
In the meantime, we’re sharing out early test plans for some major features. Before I get you all excited about early availability, please know that what’s currently available is not the release candidate. By definition, development versions are riskier than release candidates, and do not necessarily represent what will be in the release candidate.
In particular, do not attempt to flash a development core to slot 0 unless you own a JTAG adapter and know how to use it to recover from a broken state. Keep a stable core in slot 0, and use any other slot for the development core. We’re working on making it safer to upgrade slot 0 without a JTAG adapter, but this is not yet ready for testing by people that don’t actually have one.
While it is possible to have multiple MEGA65 cores installed and switch between them, this is not the case for system software files (.M65 files) on the SD card. We haven’t noticed any issues using newer system software with the earlier stable core, but keep this in mind while troubleshooting issues.
Here are the development builds of the platform components:
You are invited to help test Ethernet file transfer, a feature in the development version of the core and tools. See these instructions for testing Ethernet-based file transfer. You’ll want to be familiar with your PC’s command line interface, as the file transfer tools are currently only available in command line form.
A few things to notice:
The core download includes a new system software file, ETHLOAD.M65, so be sure to copy that file to the SD card.
This feature exposes the MEGA65 to be controlled remotely by another computer over a network. As a safety measure, the feature is locked by a DIP switch on the main board. You will need to open the case to set DIP switch #2 to the “on” position.
You can connect your MEGA65 to your local network router, or directly to a PC using an Ethernet cable. You provide the file transfer tool with an available IP address on your local network, so you will need to know how your local network or PC networking settings are configured. Typically, the IP address of your computer’s network interface and the subnet mask together indicate the IP address range for the local network. When using a router, you will need to configure your router to reserve an IP address for the MEGA65, so that it doesn’t assign it to another device. (The MEGA65 doesn’t support DHCP directly.)
You enable a remote control session on the MEGA65 by pressing the Shift + Pound key combination. The power light will blink to indicate that it is listening to the network. You can then run the mega65_ftp command-line tool to transfer files.
Give it a go, and ask questions in the Ethernet Tools Testing thread on Discord.
The next delivery batch will include a fresh printing of the User’s Guide. We’ve taken this opportunity to overhaul the Guide, update it with new information for the v0.96 release and R5 main board, and do a cover-to-cover editing pass over the whole thing including the BASIC reference. The BASIC quick reference card has also been updated, and there’s a snazzy new cover image. There are a few remaining to-do items related to features that are still in progress.
Download the latest User’s Guide PDF, file documentation issues on Github, and discuss in the #manual channel on the Discord.
The following report attempts to summarize results while preserving the anonymity of respondents. Free text responses will be kept private and will not be quoted verbatim in this report. I will be summarizing based on my own judgement, and I will withhold outliers to preserve privacy. Please know that even if your opinion doesn’t seem represented in the report, your free text responses will still be read by the MEGA65 team.
I will attempt to base conclusions on numerical data where possible. Interpretation of free text responses will inevitably be biased. This bias reflects on me and not the opinions of the MEGA65 team. Similarly, I designed the survey and am solely responsible for flaws and biases in the way questions were structured and worded. This will be pretty casual.
The survey asked respondents whether they currently own a MEGA65, have one on preorder, are still considering placing an order, are not considering an order, or may have previously owned a MEGA65 and no longer do. Owners were shown additional questions about the configuration of their machine. Non-owners were given additional opportunities to explain their interests and concerns.
This is a control question for interpreting other responses, and is not a useful indicator of a single population on its own. The relative sizes of the categories only describe the response pool, not the MEGA65 community at large. The survey was promoted in various channels that tend to skew variously towards owners (such as the Digest, Discord) or non-owners (such as Commodore user groups), and non-owners were encouraged to reply, with the rough guidance that anyone who has heard about the MEGA65 is invited.
When the survey was sent, approximately 900 MEGA65s had been delivered. This helps extrapolate potential population counts from a sample of the owner category. 218 respondents said they own a MEGA65, which is 24% of all owners. In contrast, there is no good way to extrapolate answers from a sample of non-owners to a larger population.
For some questions asked of all respondents, ownership status has a natural influence on responses. Someone is more likely to engage with community resources after they have received their computer. For example, 86% of current owners said they are aware of the Xemu emulator, compared to 58% of respondents who have not yet placed an order.
I will try to separate results by ownership status where there appears to be significant difference. This does not intend to imply that responses from any particular group are more or less important. There are many non-owners that make major contributions to the community, as well as owners that have not yet engaged with the project. Grouping is merely a crude way to control for differences in sampling.
The survey offered a list of possible reasons why someone might be interested in the MEGA65 project, and asked for zero or more selections. Raw data from multi-select questions can be difficult to interpret, especially when the question is phrased like a buffet of ideas or desires. The survey could have asked respondents to rank these, or pick a primary reason, but that felt too limiting.
Many respondents are interested in collecting vintage computers, reproducing the experience of the Commodore 65 prototype, and leveraging the MEGA65’s FPGA to reproduce the experiences of other Commodore 8-bit computers. The MEGA65 project’s goal of staying connected to history has always been a balancing act between recreating an incomplete, unreleased, and ultimately canceled design, and completing and extending that design to be practical and fun to use in the 21st century. As invigorating as it is to see the MEGA65 as an opportunity to design a new 8-bit computer, it is important to the community that the MEGA65 project values historical preservation.
Several of the options discuss programming, which is also repeated later in the survey. Many respondents want to run MEGA65 software written by others, write programs for their own enjoyment, and/or write programs for others to use. I’m personally gratified to see 19% said they want to use the MEGA65 as a platform for learning how to program computers in general. I’m also excited to see 19% said they want to learn FPGA programming. There’s a lot of potential for the MEGA65 to be an all-in-one FPGA learning platform, especially with the MiSTer2MEGA65 template as a starting point.
We can try to relate interest in recreating Commodore computers and interest in programming.
This section included a free-text prompt for mentioning other interests and motivations. Many took this opportunity to elaborate on their interest in using the MEGA65 as a Commodore 64, and potentially other Commodore computers, with several people appreciating that new hardware is more available and less likely to fail than vintage hardware. Others gave details about their interests in programming, with some specifically interested in FPGA development. Quite a few people praised the project for its nostalgic feel, and called out wanting to participate in the MEGA65 community.
The survey asked follow-up questions to people who said they don’t use their MEGA65 or are not interested in ordering. The most common concerns are the price being too high and software being too scarce. (The survey phrased this as “Not enough software,” which was intended as “Not enough new third-party MEGA65-platform software.”) I won’t share specifics on these questions publicly due to low response rates in these categories, but all individual concerns will be seen by the team.
The survey asked owners to identify when they received their computers, to determine which delivery batch they received. We know that batch 1 (from mid-2022) and batch 2 (from early 2023) each delivered 400 units. Of these, 35% of batch 1 owners and 16% of batch 2 owners responded to the survey. This might indicate that batch 2 recipients are less engaged with our communication channels than batch 1 recipients.
(This is not to be confused with the proportions within the responses. Among respondents who said they owned a MEGA65, 64% said batch 1, and 29% said batch 2.)
I asked owners how often they use their MEGA65s. Batch 2 owners are slightly more likely to be using their computers more frequently than batch 1 owners, which would make sense if batch 1 owners have had more time to move on to other projects.
The MEGA65 platform (core, ROM, and system software) is upgradable, and the MEGA65 team continues to improve the platform and issue new releases to be installed at the factory for each delivery batch, and made available to everyone as upgrades. Batch 1 owners started out with Release v0.9 and were invited to upgrade to Release v0.95, which was the default for batch 2. We’ve tried to make upgrading as easy a process as possible, but it’s not clear how easy it is to learn that new versions are available, or learn how to upgrade.
I’m pleased to see that 72% of owners have upgraded their MEGA65 at least once. Naturally, more batch 1 owners upgraded than batch 2 owners, because batch 2 owners started with the current stable release. Quite a few batch 2 owners reported having upgraded, likely to help beta test new features. Excellent!
17% of batch 1 owners report having not upgraded. The survey didn’t ask why they did not upgrade, but given the benefits of upgrading, it’s worth taking this as an indication that these owners may not know about the newer releases, or may not know how to upgrade.
Everyone who said they have upgraded was asked what they have for their default core and MEGA65 ROM. Options included the MEGA65 stable release cores and ROMs, newer test versions of each, non-MEGA65 cores, and MEGA65-compatible ROMs such as the C65 prototype ROMs or the MEGA65 Open ROM project. In the following charts, I have included people who said they did not upgrade (and so were not asked which core or ROM they are running) in the results for the stable releases based on their reported delivery batch.
21% of owners admitted that they do not know which core or ROM (or both) that they have installed. I would guess many of these might be people who were not in a position to check their version numbers when they took the survey. This could also suggest that we can do a better job making this information easier to find. While it’s an authentic retro experience to not know or care about the chipset and ROM version of a vintage Commodore, it’s important that we help everyone keep up with updates so that they get the most out of their machines.
The survey also asked which cores everyone has installed, regardless of slot. 54% of owners have the C64 for MEGA65 core installed. Once again aggregating responses from people who said they have never upgraded:
Owners were asked several questions about their video and audio configuration, and peripherals they are using.
81% reported using the PAL video mode as their primary mode. Of these, 17% reported that their display only supports PAL.
Similarly, 18% reported using the NTSC video mode as their primary mode. Of these, 24% reported that their display only supports NTSC.
56% of owners reported that their display supports both PAL and NTSC display modes, so they can run software that switches to either mode. 24% reported that they do not know whether their display supports both modes.
The survey asked which video and audio outputs you used primarily. Some displays support more than one input. (I actually keep both DVI and VGA connected so I can switch between them as needed.)
I asked everyone to name the make and model of their display, as free-text. Not everyone knew their make or model, but many attempted to answer. I was hoping to compile a list of recommendations of displays that support both PAL and NTSC. Not surprisingly, almost everyone was using a different model of display.
The most reported single model was the Dell P1917S, a 19" 5:4 flat panel LCD display that has both DVI and VGA inputs and supports both PAL and NTSC, and you can still buy it new. It doesn’t have built-in sound, so get a pair of powered computer speakers with a 3.5 mm audio input. Note that the Dell soundbar for this model is USB audio only and won’t work with the MEGA65. I have used this model, as well as a vintage Dell 2001FP with an older soundbar with a 3.5 mm audio jack. I can report that the P1917S handles the VGA signal much better than the 2001FP, and the P1917S doesn’t freak out about sound over HDMI either the way the 2001FP does for DVI video.
I also asked about video capture equipment. Only a few people said they use it, primarily for making or streaming video of their MEGA65. Generic HDMI-to-USB capture devices seem to work just fine. I use an Elgato Cam Link for this purpose, and I got a ClonerAlliance Box Pro based on a recommendation from retroCombs which I also like a lot.
I asked everybody (not just owners) about what’s in their closet, in an attempt to survey what people can be expected to own that would extend their MEGA65 experience.
In general, lots of respondents have joysticks, and quite a few have mice and paddles. 11% reported not having any of these.
Of the paddle owners, 57% have Commodore paddles, and 41% have Atari paddles. Great job knowing what paddles you have! It was only last year that I learned there was a difference. As a kid I used Atari paddles with my Commodore and didn’t understand why my paddles had about half a turn of dead space.
Many respondents, 68%, own a vintage 5-1/4" Commodore disk drive. I included a free-text field for other IEC devices, and plenty of people reminded me that SD2IEC devices are popular. Zero respondents reported owning a vintage dual drive unit, such as the Commodore 4040.
I asked how many floppy disks you own, of any type and for any purpose. 62% said they have more than 20. 14% have none. I intended this as a rough measure of how many people might use the built-in floppy drive. Of course, the drive could still be used with a future purchase of MEGA65 software distributed on 3-1/2" floppy.
88% of overall respondents said they could connect a MEGA65 to their local network via Ethernet from where they use a MEGA65, or from where would use one if they had one. Those new networking features of the MEGA65 will be a game changer for transferring files without extracting the SD card, and for doing cross-development. Anyone without convenient access to an Ethernet connection might be able to use a Wifi-ethernet bridge.
29% of owners have a JTAG adapter for their MEGA65. 11% of owners have a UART serial adapter. JTAG and UART serial are powerful tools for programmers doing cross development and contributing to the MEGA65 platform, and some have used them just to transfer files back and forth between their PC and their MEGA65. The new Ethernet-based tools can move files and programs at much faster speeds, and are likely to eliminate the need to buy extra hardware for most people. JTAG is still needed for testing bitstreams, and JTAG/UART are still useful for remote debugging tasks, at least until someone makes a similar feature that works over Ethernet.
Small but non-zero percentages of respondents own a MEGA65 DevKit, and/or a Nexys or Wukong FPGA development board, all of which are alternative ways of running the MEGA65 platform.
The survey asked how many MEGA65 software titles have you downloaded off of the Internet. It asked this of all respondents, not just MEGA65 owners, because some people use the Xemu MEGA65 emulator as a temporary or permanent substitute for MEGA65 hardware.
12% of owners say they have never downloaded MEGA65 software. 71% of non-owners have never downloaded software, which makes sense. The non-owner sub-categories break down as you would expect, with greater degrees of interest in the project correlating with more software downloaded.
Retro software publisher poly.play currently prints two commercial titles for the MEGA65: Hibernated 1 by Stefan Vogt, and Showdown by Badger Punch Games. 14% of respondents have purchased at least one of these. 6% of respondents have purchased both titles. 40% knew about them but did not purchase either, and 45% did not know about one or both.
The Xemu MEGA65 emulator by Gábor Lénárt (LGB) is the definitive PC emulator for the MEGA65 platform. 74% of respondents knew there was an emulator before taking the survey. Of the people who said they knew about Xemu, 48% said they use it.
There are several reasons people use Xemu, so the survey asked about them.
Selecting just for people who already own a MEGA65, the proportions of uses don’t actually change much except, of course, for respondents stating they use Xemu because they don’t own hardware.
The survey gave everyone an opportunity to provide feedback on Xemu. We collected dozens of excellent suggestions and feedback in a wide variety of categories. Xemu is a well-loved tool and a cornerstone of the MEGA65 project, and we’re all grateful to LGB for working on it!
Every MEGA65 ships with a first edition printed User’s Guide. 28% of owners use it regularly, 44% refer to it occasionally, and 26% rarely or never use it.
The User’s Guide is just one of a set of books in progress that form the complete documentation for the project. The latest versions are available as PDF files, free for anyone to download. The survey asked all respondents how often they use the PDFs.
When I first got my MEGA65 in May of 2022, I wrote Dan’s MEGA65 Welcome Guide as a supplement to the official documentation, intending to patch over the gaps between the intended experience and the first delivery batch that I knew would be fixed in later versions. It ended up being a generally useful resource for many. 62% of respondents were aware of the Welcome Guide.
The survey asked about what medium you prefer your documentation. My personal preference would be professionally printed manuals, and the MEGA65 documentation was set up to maybe someday become a multi-volume printed set, similar to the printed User’s Guide. I wanted to gauge interest in crowdfunding a professional print run. Crowdfunding can be tricky with a small population, especially one that’s difficult to reach. Print-on-demand services are easy to use with no up-front or on-going monetary investment, and they have significant advantages for global fulfillment, but they’re lower quality than what I have in mind. My favored option for printing would require a minimum print run.
In the survey, I proposed a hypothetical version of this project where an “entire set” (with the actual content to be determined) might cost $150 USD, and individual volumes might cost $35 USD. I asked everyone their preference: the entire set, a couple of volumes, print-on-demand, or digital only.
If the responses are representative of the preferences of everyone who will own a MEGA65 by the end of 2023 and enough of them could be reached to announce a crowdfunding campaign and at least half of them backed the project, we could make fancy books a reality. It’d be a limited print run, followed up by a secondary print-on-demand version available in perpetuity. I like these odds well enough. Even if the crowdfunding campaign never happens, investing in content will improve the digital versions and we can easily do an official print-on-demand offering when we feel they’re in a state worth printing.
I’m also going to try to get a web version of the documentation working. No promises—it’ll be a chunk of work to clear up the LaTeX for web export—but it’s a worthy goal.
If you’re reading this, you’re probably aware of my monthly email newsletter, Dan’s MEGA65 Digest. I initially announced the survey in the Digest, so it’s not surprising that 60% of respondents were aware of the Digest before the survey. I’m delighted to see that 39% of respondents were unaware, because that means two things: 1) there are more people out there who might be interested, and 2) our efforts to promote the survey reached beyond people already aware of the Digest.
Of the people aware of the Digest, 67% read the text version by email. 15% go to my website directly, and a few use RSS or the Substack website. It’s good to see that I could migrate the Digest to another newsletter provider if needed and probably nobody would miss it.
Did you know that there’s an audio podcast version of the Digest? 42% of people familiar with the Digest did not know. 18% listen to at least some issues by audio. 51% of listeners use the Substack service to do so (because clicking on the email takes you there), and 37% of listeners use a podcast app. I enjoy making the audio version and I’m grateful that some find it entertaining.
Thank you all for the generous comments in the free-text field! Some people asked for more advanced technical topics, and others asked for less advanced technical topics. 😊 Several people mentioned interest in a print anthology, or just a printed zine. I’m not sure I could fill a print zine each month—at least not without collaborators.
62% of all respondents are aware of the MEGA65 Filehost, an essential community resource. 91% of owners who responded to the survey know about it.
Of those who are aware, almost everyone has used the Files section to browse and download files. 47% of respondents who own a MEGA65 have redeemed their owner code, which is surprisingly low! You need to redeem your owner code to access release packages containing the closed ROM (though there are other ways to get the closed ROM). The survey asks about other features of Filehost, and it generally looks like people use them proportional to the amount of material posted in those categories. No surprises here.
83% of all respondents are aware of the MEGA65 Discord, and 54% have an account. Of those that have an account, 29% visit it daily.
76% of all respondents are aware of the MEGA65 section of Forum64.de, and 33% have an account. Of those that have an account, 18% visit it daily.
25% of all respondents have both a Discord account and a Forum64 account. 75% of them visit the Discord at least once a month. 28% of them (7% of all respondents) visit the Discord daily.
The majority of respondents have more than 10 years of experience writing computer programs. The survey purposefully did not make a distinction between professional vs. hobbyist programming: the survey used phrases like “writing computer programs” to be inclusive of both.
79% of all respondents said they are interested in writing their own programs for the MEGA65. Those that expressed interest were presented additional questions about programming tools.
Of those that want to program, 75% are interested in assembly language, and 75% are interested in BASIC 65.
The survey offered a free-text box to express interest in other programming languages. Python was mentioned multiple times. In my experiences with Python and with retro computing, I’ve seen many people wonder aloud if MicroPython could be ported to a vintage computer. In those discussions, the quality of C compilers that target retro platforms has been mentioned as an issue, so I wonder if it’s a topic worth revisiting in the context of llvm-mos. Pascal also got multiple mentions, which is more likely to be built from scratch for the MEGA65 by an enterprising hobbyist.
The survey listed a bunch of popular cross-development tools and let everyone pick their favorites. Visual Studio Code, CBM prg Studio, Kick Assembler, and cc65 were top of mind for most people. Several people mentioned C64 Studio in the free-text responses.
I know people that love cross development, writing programs for the MEGA65 using a modern computer. I also know people that love on-device development, preferring to shut off the modern computer and use the MEGA65 as its own programming environment. The survey asked for your preference, and results were split three ways: on-device development, cross development, and “depends on the project” all got roughly the same proportion of responses.
65% of respondents are between 45 and 54 years old. Remaining respondents are roughly split between 35-44 years old and 55 years or older, with only a few respondents in other age groups.
The MEGA65 community is international, with strong contingents in Germany and the United States.
Discussion about the MEGA65 on Forum64.de is almost entirely in the German language, and making MEGA65 programming resources available in the German language is a frequent topic of discussion. For the survey, I asked two questions about spoken language: in what language(s) do you prefer to socialize online, and in what language(s) do you prefer to consume technical information?
86% of everyone who answered these questions answered both questions with the same language or languages. 80% of these said English. 7% said they preferred German exclusively for both. 10% offered both English and German as their answer in both categories.
14% of respondents gave different answers for preferred languages for socializing vs. technical information. Of those that gave different answers, 85% said English was preferable or at least acceptable for consuming technical information. 13% preferred technical information in German.
Danish, Dutch, English, Finnish, French, German, Hungarian, Italian, Norwegian, Polish, Portuguese, Scandinavian, Spanish, and Swedish were all mentioned at least once. I won’t draw any conclusions due to sample size, but it’s exciting to list them all out!
The survey asked for everyone’s preferred social media service. This is a bad question. Outside of the Digest, the survey was promoted almost exclusively on social media, and so response rates are most likely to correspond to visibility of the survey announcements on those platforms. Nevertheless, it’s good to know that Facebook and X.com (née Twitter) are still important ways to reach people.
Despite how the survey was promoted, 22% of respondents say they do not use a social networking service. There was some ambiguity in the question about whether Discord qualifies as social media. The survey did not include it in the list, but it included a free-text prompt for other services and many used it to mention Discord. Combining social media non-users and users of services the survey did not list, that’s 28% of respondents.
Nearly every respondent has owned or used a Commodore 64 in their lifetime. 76% of respondents currently own a Commodore 64. Only 2% of respondents have never owned or used a Commodore computer.
45% of respondents own an SD2IEC device. 35% own an Ultimate 1541 (any model). Of potential interest to future MEGA65 cartridge authors, 21% of respondents own an EasyFlash 3, and 10% own an EasyFlash 1 or 1CR (purchase link).
34% own, have preordered, or intend to order at least one of several retro-style modern computers that the survey listed. The breakdown between the models isn’t interesting, mostly corresponding to the current availability of those machines.
53% of respondents use a Windows computer. 22% use an Apple laptop or desktop. 20% use a Linux laptop or desktop.
Of the Windows users, 44% are using Windows 11, and 52% are using Windows 10. Several people are using Windows 7.
Of the Apple users, 73% have an Apple Silicon (M1 or M2) processor, and 26% have an Intel processor. 53% are using macOS 13 Ventura, the latest stable release. 31% are on the macOS 14 Sonoma public beta. 13% are using older versions of macOS.
I did not ask about Linux distributions or variants, nor did I ask about Intel vs. ARM for Linux or Windows. Tablets (iOS, Android), BSD variants, Windows Subsystem for Linux, AmigaOS 4.1, and MorphOS were represented in the minority replies.
The survey concluded with an invitation to provide free-text feedback to the MEGA65 project. I will try to summarize common themes and provide my own commentary based on my experiences with the project in the last year. This will naturally reflect my own biases.
Enthusiasm. Nearly everyone took this opportunity to express words of encouragement and praise for the project. Thank you all for your kindness and generosity! It is gratifying to know there are so many people out there who believe in the MEGA65 project and are enthusiastic about the community and what everyone has accomplished so far.
Price and shipping cost. As of this writing, the MEGA65 production model, with the mechanical keyboard, injection molded plastic case, and built-in 3.5" floppy disk drive, has a retail price of 666.66 € ($722.38 USD), not including taxes or shipping costs. The total cost to buy one delivered to where I am in the United States is 790.20 € ($856.79 USD). This price alienates some people who are interested in the project, due either to the value proposition or the ability to pay. Less expensive options include running the MEGA65 core on a Nexys Artix A7 FPGA development board, or running the MEGA65 ROM in the Xemu emulator. The central FPGA chip dominates the price, and burning the chipset design into cheaper ASICs would require several orders of magnitude more people interested. (And of course, ASIC-based computers would not be upgradeable.) Counterintuitively, eliminating the floppy drive does not meaningfully reduce the cost, and new plastic case shapes would require an up-front investment in new moulds.
Shipping delays and shipping updates. Many who have preordered a MEGA65 have experienced shipping waits longer than one year. Estimating shipping dates has been nearly impossible over the past two years due to the unavailability of essential components, and a reliable estimate is only possible after all parts have been acquired by our assembly and distribution partner Trenz Electronic. Trenz has been great about responding to customer service inquiries with rough guesses, but it is not currently a regular practice to send periodic emails to pre-order customers during the process. Some survey respondents expressed concern about the lack of proactive order status communication. Due to privacy laws in Germany, Trenz Electronic is not allowed to share their list of pre-order customers with the project team. The best we’ve been able to offer so far is to use other communication channels to encourage everyone to subscribe to the newsletter or follow project announcement channels on the Discord, YouTube, or Paul’s developer blog. It has been a challenge to make sure pre-order customers are aware of these resources.
Sources of technical information. The MEGA65 has a substantial amount of technical documentation available, but this can be difficult to notice given how that information is stored and disseminated. Survey respondents pointed out that having information spread over PDF manuals, a Confluence Wiki, and Filehost articles is inconvenient, and it’s unclear where to find each kind of information. Sometimes the easiest way to get an answer to a technical question is to ask the Discord chat, but answers to questions previously asked are difficult to find, and both the community and its discussion archives are only available to Discord users. Discord is an ephemeral medium and does not function as a technical resource, at least not a passive one, and it’s unreasonable to expect all users to read every discussion. Moreover, none of these resources are reliably indexed by search engines, either by design (Discord cannot be crawled; Confluence blocks crawlers) or by unintended technical limitations. Multiple survey respondents wished for a more traditional open-access web forum, and some are disappointed that only a subset of the community participates on Forum64.de.
Better software. Many MEGA65 owners want to use their computer to run games and applications written by others. Without a large library of quality titles (for some relative definition of “quality”), the MEGA65 is mostly useful for learning to program, writing programs from scratch, or running C64 software via the C64 core (or GO64 mode). Some respondents emphasized that they would be willing to pay for quality MEGA65 software. Some respondents said they are waiting for the software library to grow before investing in a purchase.
German-language technical resources. Multiple respondents used the free-text feedback field to emphasize the need for German-language technical information. There is a German MEGA65 handbook that is highly valued. The topic of German-language video tutorials, livestreams, and classes comes up occasionally on Forum64.de.
Technical issues. Several respondents mentioned some of the common technical issues we have experienced in the first year, both in the electrical hardware and in the core and ROM. The new main board revision will help with some of these, and the core and ROM are active projects that welcome contributors. Many respondents expressed gratitude for everyone who is contributing fixes, and are excited to see the work continue.
Feature areas. Many respondents were excited about the potential for new features, including networking applications, D64 disk image support, more alternate cores, and more on-device programming environments and tools. Several respondents wished for more programming tutorials and recipes. Several respondents expressed an interest in a more compact version of the keyboard case without the floppy drive. Others reminded us that some owners of R3A boards would be interested in buying a bare R5 board as an upgrade. (I considered asking about interest in an R5 upgrade as a survey question, but we don’t know how much such an upgrade would cost. We don’t realize economies of scale in the hundreds of units, so it doesn’t help to forecast sales.)
More community events and publications. Respondents expressed an interest in more live streams like the MEGAVISION live stream that took place earlier this year. Conferences were also mentioned. There were multiple suggestions for a print magazine.
One of the biggest questions I wanted to answer with the survey was, how effective have we been at connecting the MEGA65 community with the project, and how can we improve? Communities around projects tend to form layers of engagement, and we want to foster the growth of all of those layers and reach as many people as possible that would benefit from the project. We have known issues with making resources available in search engines and providing information to pre-order customers. We can only hope that as people get more interested, they look for community resources more aggressively.
The first test was simply, how many people can we get to take the survey? 509 respondents feels downright miraculous considering that only 900 people currently own a MEGA65 (DevKit or production model). We aren’t privy to the number of pending pre-orders but we believe it is over 1,000. The survey promotion reached quite a few people who are interested enough in the project to take the survey but have not yet pre-ordered, but it’s impossible to guess the size of that population from the survey alone.
Our limited ability to reach out to the community makes it difficult to promote resources like Dan’s MEGA65 Digest, and difficult to promote community projects that require financial support. A small number of free-text responses in the survey ask for things that already exist, which suggests that we could be doing more to promote the resources we already have.
The survey asked about several specific community resources, projects, and concepts, and made a distinction between “I know about that resource but don’t use it” vs. “I didn’t know about that resource.” These replies are a useful indicator of how well information about the project has disseminated. The following numbers are shown as percentages of owners. Owners are more likely to be familiar with resources, and have a known population size as a basis for the sample. This is not meant to exclude non-owners from consideration, only to have a basis for comparison.
The MEGA65 is an open source volunteer-run project. It doesn’t have development resources so much as interested parties. Nevertheless, many people who work on the project want the project as a whole to succeed, and want to work on important things, so seeing which tasks can have the most impact can influence contributors.
I can’t speak for anyone else, but personally, I’m more motivated to work on information visibility. This was already my area of focus with the Digest. I have ideas for making our information easier to find in search engines, and I hope to use my web development background to improve our web-based resources and community tools. I also want to evolve the Digest to make it more visible and interesting to a larger audience. The Digest is our primary tool for disseminating news and project status—including best available information on shipping updates—and I want everyone who is interested in the project (at any level) to at least be aware of it.
I’m excited to see that we might be able to afford a high-quality print run of the manuals, if we can finish them. Print books are a fun addition to the retro experience, and they’re one of my favorite things to make. It’s good to be reminded by the data that many people would prefer browser and e-reader-friendly resources, and hopefully we can produce both print and web resources using the same content.
There’s an opportunity for German content creators to fill a need. Bloggers, YouTubers, and live streamers capable of producing tutorials and walkthroughs in German—at any level of technical complexity or production value—could have a big impact. I’ve seen people ask for German-language BASIC programming introductions on Forum64.de. You don’t need to know a ton about the internals of the machine to help others with their first steps, and simply blogging your own learning adventure can attract a grateful audience. We can also consider crowdfunding a professional German translation of the manuals once they are reasonably complete.
There’s no shortage of interest in improving the platform or the hardware, just a shortage of time. I believe our open source processes are in decent shape, so if anyone is interested in helping out, please reach out on the Discord. Bug reports are always welcome, even if you are unable to submit bug fixes.
As for growing the software library, the number of owners is expected to more than double by the end of the year. It’ll be exciting to see what everyone comes up with!
That’s it for this year’s survey! Thanks again to everyone who responded. Let me know if you have any feedback on the survey itself or this report. We might do this again next year.
— Dan
The MEGA65 Community Survey 2023. Dan’s MEGA65 Digest for August 2023.
Hey all! I’m keeping this issue short, because there’s something more important for you to do instead of reading.
The MEGA65 Community Survey 2023 is now open. This survey is for anyone even a little bit interested in the MEGA65, whether you own one, have preordered, are still considering it, or don’t intend to order but still enjoy seeing what’s going on. This includes anyone not subscribed to this Digest, so please share this link.
Responses are anonymous. We will share aggregate anonymized results in a future Digest. Full-text replies will be kept confidential to the MEGA65 Steering Committee.
We’re targeting 400 responses for this year’s survey. If everyone subscribed to the Digest responds, we’ll hit that easily. (Please only take the survey once, so we get accurate counts.)
Here’s that link again: please take the survey. Your response will go a long way to guiding the future of the MEGA65 project. Thank you!
After you have completed the survey, it’s time to hit the arcade! Run don’t walk to the Galaga core for the MEGA65 by muse. This isn’t just a version of Galaga for the MEGA65, this is Galaga, a port of the original arcade hardware architecture running directly on the MEGA65 FPGA. The core even supports connecting a vintage VGA monitor turned on its side to fully replicate the arcade experience.
Installation requires a few steps, including fetching the original Midway Galaga ROM from the Internet (using the link provided) and running a Python script. See muse’s installation instructions.
When starting the core, give it a minute to go through the arcade hardware test routine. The core displays its keyboard controls briefly; press the spacebar to dismiss. Press 5 to insert a quarter, then press 1 to start a one-player game. You can control the game via a joystick in port 1, or use the keyboard: A and Z move left and right, and the Cursor Up key fires. The P key pauses. As with the C64 core, press the Help key to open a settings menu.
Huge thanks to muse for this effort, and to all of the original implementors of the core. (And to Midway too, but they already have all of my lunch money.)
Last month I mentioned that there will be a new revision of the main board that will start shipping with the next delivery batch, known as R4. Due to restricted availability of a component, the board needs one more revision. This gives us an opportunity to further refine the cartridge interface before the revised board goes into production, so we’re taking that opportunity. The core needs a corresponding adjustment, so the board is now known as “R5” to distinguish between the core builds. R4 boards will not be manufactured. The next delivery batch will receive R5 boards.
The cartridge interface enhancements will make it possible to support fancier utility cartridges. As with the other revisions, only time will tell what differences will actually be notable in practice. The most important reason to know which main board revision you have is to download the correct versions of core files.
I said I’d keep this short, but I can’t resist including a bit of BASIC fun.
Of all the Commodore 64 games that could have been a staple of my childhood, an unlikely contender was “Pudding Mountain Miner” by Charles Brannon. Brannon was an editor for Compute!’s Gazette magazine, and originally wrote “Pudding Mountain Miner” as a short type-in to appear in newspapers promoting the magazine when it was getting started. He wrote up an explainer in the April 1985 issue of Gazette, in the “Horizons” column.
The game is a one-button shooter where you’re a fighter pilot dropping bombs on Pudding Mountain, digging for buried treasure. If you hit the dollar sign, you win the big bucks. If you hit the mantle underneath the pudding, it’s game over.
I liked Miner because it was fun and cute, and also because it was only 17 lines of BASIC code. I don’t think I ever bothered to save it to disk. I would just type it in any time I wanted to play it.
Here’s the program listing converted to a form where you can use it with petcat to generate a PRG in case you don’t want to type it in (but what’s the fun in that?). This version runs just fine with the MEGA65’s GO64 mode.
Brannon’s article gives a line-by-line description of how the program works. I’ll try not to repeat the whole analysis, but I do want to notice a few things.
For starters, it’s difficult to read. Brannon wrote this to appear in a newspaper ad, so he used Commodore BASIC’s abilities to combine multiple statements on a single line and omit spaces to cram all of the code into a dense rectangle. C64 programmers are accustomed to omitting spaces because it speeds up the program slightly when running at 1 MHz, and it uses slightly less BASIC memory. At the MEGA65’s 40 MHz, omitting spaces makes no measurable difference and isn’t worth doing.
Early Commodore BASICs lack built-in commands for graphics and sound, so programs like games tend to contain many POKE statements. As a result, very few lines of code say what they mean, at least to a reader that didn’t write the program. To work backwards from an obscure statement like POKET+Q,160, you have to recognize that this actually says POKE T + Q, 160, that the variables T and Q are forming an address, that T is assigned the number 1024 under some circumstances, and that this is the start of C64 screen memory. Then you know to look up a screen code table to determine that the value 160 represents a blank space. This statement is probably writing a blank space somewhere on the screen determined by the Q variable.
I’m not criticizing the way the program is written. If anything, I’m criticizing the way programs had to be written for the Commodore 64, at least under some circumstances. Of course, Brannon intentionally wrote this program to take up as little printed space as possible, so it is designed, crunched, and organized in an atypical way.
One of the most interesting parts of the program is this bit in the very first line: V=(PEEK(0)=76) When this runs on a Commodore 64, the V variable is set to 0. Some simple arithmetic determines how the other variables on this line are set: W is set to 40, T is set to 1024, C is 55296, S is 53281. 40 is the number of characters that fit on a single line of a C64’s screen, so W probably stands for “width,” and sure enough that’s what it appears to mean elsewhere in the code.
But what’s up with the PEEK(0)? It turns out that this program also works on the VIC-20! When this runs on VIC-20 hardware, PEEK(0) evaluates to 76, so the comparison PEEK(0)=76 evaluates to true, so the V variable is set to -1, which is how “true” is represented in Commodore BASIC. This affects the settings for the other variables: W=40+18*V becomes 22, which is the screen width for the VIC-20.
This game takes advantage of the similarities between the C64 and VIC-20, along with some intentional design choices, to scale its display to fit the computer it’s running on. This poses a question: what’s the smallest change we can make to this program so that it runs on the MEGA65 in 80-column mode?
On the MEGA65, the BASIC syntax is the same, the PETSCII character and screen codes are the same, and the VIC-II registers are present at the same addresses by default. Screen memory is relocatable and not at the same location by default, so we’ll have to do something about that. Color memory (whose location is stored in the C variable) needs to be accessed at a different memory location if we want to access the full 80 column’s worth.
Let’s just try this and see what happens:
(I’m using hexadecimal values here because I’m used to thinking of these addresses in hex, and BASIC 65 supports hexadecimal value literals.)
I had read through the whole program to make sure this would work and was still surprised that it did. There’s only one issue: it’s way too fast! We need to slow down the MEGA65 processor to make it playable. Thankfully, this is possible with a BASIC 65 command.
It’s the nature of this game that the denser character width makes it more difficult to hit the target, but it works! No other changes are necessary.
Consolidating this into a single BASIC listing that works on all three machines would be straightforward—or not so straightforward if you want to preserve the compactness of the original. I’ll leave that as an exercise.
That’s it! Next month should be action-packed: we’re about to open public beta testing of the next major platform release. I’m trying to do my part and fix as many bugs as I can before the deadline. Of course, this is an open project, so you can get involved with testing right away if you like. Inquire in the Discord.
Go take the survey, and tell your friends. See you next month!
— Dan
Cross Development for Fun and Profit, part 2. Dan’s MEGA65 Digest for July 2023.
In last month’s Digest, we introduced cross development, the practice of writing MEGA65 programs using a modern PC. We looked at several tools for writing programs in the BASIC 65 language and in 45GS02 assembly language, and we welcomed a new BASIC-like compiled language with MEGA65 support called XC=BASIC.
Let us take one step further into the world of compiled languages. The C programming language is one of the most widely used programming languages in computing history, suitable for everything from microcomputers to mainframes. It was the language that built the Unix operating system—or maybe it was the other way around. Fifty years later, C is still in widespread use, for better and for worse.
As fun as it is to write in assembly language, larger programs benefit from a language with a bit more structure to manage the inherent complexity of software. There are several cross-development tool chains for writing Commodore programs in C, and these can also be used to write programs for the MEGA65. In this issue, we will try using one of these tools to write our first C program, and walk through the concepts involved. We’ll look briefly at other tools and resources for getting started with C programming for microcomputers. And we’ll consider a much newer language vying to be the C of the next fifty years, called Rust.
We’ve been talking about coding tools lately, so let’s do an all-tools edition of Featured Files!
The Coffeebreak Compiler, by TOS22.
The Coffeebreak Compiler by TOS22. Matthias wanted a comfortable way to hack on assembly language code directly on his MEGA65 that he could extend with modern conveniences. The result is a lightly structured custom language and IDE that accepts inline assembly code and produces machine code programs, similar to ubik’s Eleven for BASIC. Press the Help key to browse the built-in documentation and tutorials.
MEGA65-Forth alpha, by carthibar.
MEGA65-Forth alpha by carthibar. MEGA65-Forth is a project to build an interpreter and interactive environment of the Forth programming language for the MEGA65. This is an early release with some features still in progress, but enough has been implemented to start learning the language. It is based on FIG Forth 1.1. Check out the source code and release notes on Github, as well as the Getting Started documentation.
bf65, by dddaaannn.
bf65 by dddaaannn (that’s me!). The experimental minimalist programming language known as Brainfuck was invented by Urban Müller in 1993 as an attempt to design a language with as small a compiler as possible that is still Turing complete. The language is famous for its funny name and for having only eight parameterless instructions. I was motivated to write bf65 when I had the idea to take advantage of the MEGA65’s built-in BASIC editor as the editor for bf65 programs, including the ability to combine BASIC and bf65 code in the same program. The D81 disk image includes the bf65 interpreter and several demo programs. See documentation and source code on Github.
C64 for MEGA65
We’ve mentioned the Commodore 64 core for the MEGA65 a few times in this Digest, and with good reason. For many owners, the potential of the MEGA65 to be an FPGA-based multi-Commodore platform is a major attraction, a chip-level recreation of an entire line of vintage computers that share a non-PC keyboard layout, made from all-new components and modern hardware conveniences. The Commodore 64 core by MJoergen and sy2002 is a huge step toward this potential.
C64 for MEGA65 version 5 is now officially released. For installation instructions, see the May issue of the Digest, and the excellent documentation.
Don’t miss the epic video trailer for the new release!
MEGAVision!
The first ever MEGAVision live streaming event took place on July 1st and was a huge success! Hosted by RetroCombs, Gurce, and lydon, MEGAVision featured nine short talks about MEGA65 projects. Watch the replay online, then visit the MEGAVision wiki page for links to resources for everything discussed in the presentation. I was happy to present my bf65 toy language interpreter at the event.
This was so successful that we’re excited to do another one sometime soon. Start thinking about topics you’d like to know more about, or topics you’d maybe like to talk about at the next MEGAVision. If you have an idea for a talk, send a message to Gurce or lydon on Discord.
Huge thanks to the organizers, to everyone who gave a talk, and to everyone who attended!
The MEGA65 main board, revision 4.
The MEGA65 project continues to invest in improving every aspect of our favorite computer. On June 30, Paul posted an in-depth article to his developer blog describing some of the recent improvements made to the design of the MEGA65 main board. The next revision of the main board, known as R4, will start shipping with the next delivery batch later this year.
Several of the improvements in the R4 board are electrical. There’s a fix for an HDMI back-power issue, improved audio quality from the 3.5 mm jack, a new Real-Time Clock (RTC) unit, and improved RF shielding for the major components. The design has also been reworked to use one fewer FPGA chip. These changes resolve some minor issues, but they otherwise do not affect the operation of the computer.
Two changes enhance the capability of the system slightly. There is now additional RAM hardware that can be used by FPGA cores, enabling porting of a larger variety of MiSTer cores in the future. Also, the joystick ports are now bi-directional, a capability used by a few peripherals like the Protovision Protopad and the Commodore version of the AtariLab science kit that I had as a kid.
Nothing about the MEGA65 platform changes with this revision. Any program written for the MEGA65 will run on both R3 and R4 boards. While the RAM hardware is intended to enable broader development of alternate cores, no core currently exists that needs it, and it’ll be a while before one does. Moreover, future cores that don’t need the extra RAM are unlikely to use it, so that they will work on all MEGA65s.
Nevertheless, it’s natural to wonder: will MEGA65 owners with the R3 main board be able to buy the R4 board as a replacement? Hopefully someday! The first priority is to fulfill all of the remaining preorders for complete MEGA65s. Beyond that, it’s not obvious that Trenz Electronic can feasibly stock spare parts, especially pre-assembled main boards with expensive FPGAs. So far, preorders have been fulfilled in batches, and it’ll take time to figure out the costs, risks, and logistics of switching to an in-stock distribution model. I know I’d love to be able to someday buy MEGA65 parts for upgrades, repairs, and building new machines with custom configurations.
For now, I’m excited by how the R4 main board is an investment in the MEGA65’s continued success. More than anything else, it means we will all get more out of our computers, no matter which version we have.
A compiler is a tool that takes a computer program written in some programming language and generates an equivalent program for the target platform’s machine code. You can write a program in the C programming language, then use a C compiler to generate the equivalent machine code program for the MEGA65.
As with other development tools, a compiler could be a program that runs on the target device directly, like how Mega Assembler runs on the MEGA65. There is not yet a C compiler that runs natively on the MEGA65, but it is possible to use a cross development workflow as we did in the previous issue of the Digest. You create a source file on our PC, then use a cross compiler to generate a MEGA65 PRG file.
As much as I want to, I can’t fit a full C language tutorial in this Digest. Nevertheless, let’s start with a small C program, so we have something to play with:
Put this in a file named hello.c. This is our source file.
Most C programs consist of multiple source files, with filenames ending in .c for definitions and .h for declarations (“header” files). Exactly one .c file defines a function named main(), which is where the program begins. A source file can #include header files to learn about functions provided by other modules. In this case, #include brings in the declarations from a module of the C standard library, including a declaration for the puts() function used by the main() function. Refer to any good book on C programming for an explanation of how C programs are organized.
An ideal compiler targeting the MEGA65 would know all about the inner workings of the MEGA65’s CPU, so it can use all of the CPU’s features in its machine code. So far, nobody has written a C compiler that targets the MEGA65 specifically. Instead, we’ll take advantage of the MEGA65’s Commodore lineage and use a cross compiler that targets earlier Commodore computers. Several Commodore cross compilers can be adjusted to generate programs that run on the MEGA65.
llvm-mos by Daniel Thornburgh and John Byrd is a cross compiler toolchain for target platforms based on the 6502 CPU. It provides a version of Clang for compiling C programs. Thanks to Mikael Lund (wombat on the Discord), llvm-mos supports building programs for the MEGA65. It supports generating code for CPUs in the 6502 lineage up to the 65C02, which will run fine on a MEGA65.
Visit the llvm-mos Github page, then scroll down to find the download link for your PC’s operating system. As usual, macOS requires an additional step to allow unsigned command line tools to run. A complete procedure for macOS users:
As noted in the llvm-mos documentation, you can add the bin/ folder to your command path for convenient access. macOS users, heed the warning that doing so may conflict with other versions of the Clang compiler you may have installed. The Apple Xcode Command Line Tools provide another version of Clang, and you may have this installed if you use Homebrew even if you don’t otherwise use Xcode. You do not need to have llvm-mos on your command path to use it: simply provide the full path to the llvm-mos commands when using them.
You can compile the hello.c example program with the following command:
This produces the file hello.prg that you can run in Xemu or on your MEGA65, as we discussed in the previous issue. It loads to the top of BASIC memory with a BASIC bootstrap header, similar to the one we used for our assembly language program.
So far, a compiler sounds a lot like an assembler: it takes a source file and produces a PRG file that does what we want. What’s different is how the tool decides what machine code to generate. When we write a program in assembly language, we must say exactly which machine code instructions the target machine’s CPU should execute. Assembly language mnemonics like LDA represent machine code instructions in a somewhat-human-readable syntax, and the assembler translates the assembly language to machine code, one instruction at a time.
When you write a program in a compiled language, the compiler reads through your program, then decides which machine code instructions will do what you intend. You can ask llvm-mos to show you the assembly language program that it came up with for your C program with this command:
This generates an assembly language listing as the file hello.s. Open this in a text editor to see the result. It is quite large because it includes the code for the puts() function from the standard library.
To get a better idea of what compilers can do, consider a simpler program that doesn’t involve a call to a large function:
There’s a website called Compiler Explorer, aka “GodBolt.org,” that can show C code and the compiled assembly code side by side directly in your browser. It supports many compilers and target CPUs, including llvm-mos and the MEGA65, so you can see the result in 6502 assembly language.
Follow this link to see one possible version of square() and main() produced from this C code.
In this example, you can see how llvm-mos converts the square() function into several dozen instructions. The labels that begin with two underscores, such as __rc0, refer to addresses in the base page that llvm-mos sets up to be used as temporary variables by the generated code. Later in the listing is the implementation for the main() function that sets up the argument (5), calls the square() function, and ends with the result in a variable. The C language requires that the main() routine returns a number, which is used by some operating systems as a result code from a program. The MEGA65 just ignores this return value.
But that’s just one possible assembly language program. Check out this version with the -Os flag enabled.
Given the -Os flag, llvm-mos generates different assembly language code for the same C program. It’s much shorter and much faster than the previous version. How can a compiler look at the same program and produce two drastically different results?
In the first version, llvm-mos took our C program literally: we wrote it as two functions, so it generated code for two functions. In this new version, llvm-mos studied the C source code, realized that this program always returns the number 25, so it produced machine code that returns the number 25. Both of these assembly language programs are equivalent to the original C program: they both return 25.
An optimizing compiler uses many complex techniques to calculate the smallest and fastest machine code possible that is equivalent to your original program. The -Os flag enables all of llvm-mos’s optimization rules. Optimization is typically smart enough that you can leave it enabled for nearly all purposes. It’s not always perfect—I can’t explain why llvm-mos generates a few instructions for the square() function in the optimized version even though it never calls them—but it’s a huge benefit.
Just as modern chess computers can play chess better than any human, modern compilers can write machine code so efficient that it’s almost not worth writing in assembly language at all. We still write assembly language programs for the same reason we still play chess: for fun.
Running the mos-mega65-clang command is fine enough for simple one-file experiments. When your project grows to multiple source files or involves third-party libraries, you will want a build management tool. CMake and Ninja are popular with the modern C crowd. (I still use GNU Make, but I’m old school.)
One third-party library you’ll want to consider early on is mega65-libc, the MEGA65 project’s own set of utility functions. This library provides functions that access files from a disk or the SD card, access memory, power a console-like user interface, and more. The library is useful enough for things like debugging that you pretty much always want to include it in your project, even if you don’t intend to use most of it. The compiler will only generate code for the functions that you use.
Thanks to kibo, there’s an easy way to get everything you need to set up your MEGA65 C project, including CMake and mega65-libc. mega65-llvm-template is a Github project template that you can either use to create a new Github repository, or just download to try it out. See the template’s documentation for instructions.
Before you dive into a good book on the C language, it’s important to note that llvm-mos has a few limitations when it comes to standard C. For starters, it does not support the float or double fractional number types. The 6502 CPU does not have built-in support for floating point math, and llvm-mos does not provide a floating point math library. If you’re ambitious, you could consider third-party assembly language routines for this purpose, such as “Floating Point Routines for the 6502” by Steve Wozniak, from the magazine Dr. Dobb’s Journal in August 1976.
llvm-mos provides a stripped-down version of the C standard library implemented for Commodore computers, using C64-style kernel calls for things like printing messages. The implementation is incomplete, and some functions may not work correctly on the MEGA65. It’s worth trying, just don’t expect everything to work.
If your C program returns from main(), either with the return statement or by allowing control to reach the end of the function, the program llvm-mos generates will attempt to return to BASIC. This doesn’t always work with the MEGA65 kernel. I sometimes get weird display artifacts, false BASIC errors, or crashes when returning from main(). Consider ending your program with an infinite loop (while(1);) and not relying on exiting to BASIC.
In C, character values ('x') and string values ("xyz") are treated as ASCII byte values. These are neither PETSCII values nor Commodore screen codes, so you will need to account for this when defining and printing text messages to the screen. Using uppercase ASCII letters in your C source code along with the MEGA65’s default uppercase character mode will print uppercase letters.
If you’re writing a game—or pretty much anything, honestly—your program will need to access registers and memory addresses directly, similar to POKE and PEEK from BASIC, or lda and sta in assembly language. This is possible in C, taking care to use C’s pointer dereferencing features correctly. Use an appropriate value type for bytes (such as uint8_t from stdint.h), and be sure to refer to an I/O register as volatile to prevent the optimizer from taking shortcuts. mega65-libc’s memory.h provides useful macros and functions for accessing registers, so it looks cleaner in your code and you don’t have to remember the details:
Programs generated by llvm-mos start by unmapping the BASIC ROM to make more room for program memory. The program code starts at address $2001, including the BASIC bootstrap program. The space beyond the end of the program up to address $CFFF is used for memory managed by the C language, a total of 44 kilobytes for both program and memory. Memory allocated by the program using the C standard library malloc() function, a mechanism known as the heap, starts just after the program and “grows upward” toward higher addresses. The stack, used for keeping track of function calls and local variables, ends at address $CFFF and “grows downward” toward lower addresses. The I/O registers remain in $D000-$DFFF, and the kernel ROM in $E000-$FFFF.
Sometimes you’ll want the ability to write assembly language code inside your C code. Clang supports the GCC inline assembly syntax, expecting to output 6502 assembly language for llvm-mos’s assembler. This requires giving the optimizer some hints about what the assembly code does, so it can make decisions about using CPU registers and relocating code. The following example from mega65-libc takes an unsigned char variable from the C code and calls a “Hypervisor trap” with a bit of assembly language, informing the optimizer that this code must be executed in this location (volatile) and that it uses the accumulator ("a"). Notice how the assembly language text is a single C string with newline delimiters (\n).
A sophisticated program might want to install interrupt handlers that call C functions, such as a raster interrupt handler that is called once per frame. This is an advanced technique that requires disabling interrupts, setting the address of the function, and updating the MAP register to disable the kernel. I won’t include a complete example here, but here’s one way to get the address of a C function as two bytes, using volatile once again to make sure the optimizer keeps the function even if it isn’t called by the rest of the program.
Enable compiler warnings. The C language gives you plenty of opportunity to make mistakes, and Clang is very smart about noticing potential issues in your code. The command line flags -Wall -Wextra -Wpedantic tell the compiler to go crazy with the constructive feedback. To enable this using the mega65-llvm-template, add this to the file CMakeLists.txt:
The most famous book for learning the C programming language is The C Programming Language by Brian W. Kernighan and Dennis M. Ritchie. Ritchie invented the C language, and this concise book is a computer science classic.
My favorite book for learning C is C Programming: A Modern Approach, 2nd edition, by K. N. King. It’s excellent for self-learning with high quality and well tested examples and exercises. I’ve literally read this book cover to cover and have done nearly all of the exercises, and I still go back to it to remind myself of language intricacies.
I wouldn’t be surprised if many of the examples from these books worked on the MEGA65, but I would be surprised if they all did. If you’re new to the C language, I would recommend starting with a C compiler for a modern computer first: Xcode for macOS, GNU C for Linux, Visual Studio Community for Windows. You will only need a subset of C’s features to write substantial programs for the MEGA65.
There are several other C compilers that work reasonably well for MEGA65 development. cc65 is popular with C64 programmers and has a long history. It is used by the MEGA65 project in many places. KickC is another, using the venerable Kick Assembler for generating machine code. Calypsi by hth313 is a C and assembly development toolkit for several vintage computers. Calypsi’s MEGA65 support is in early stages, but it already supports 45GS02 instructions, 64-bit integers (long long), and floating point math.
I chose llvm-mos for this Digest because it takes advantage of the LLVM ecosystem to have the most complete implementation of the C language and the best optimizer. With a built-in MEGA65 configuration, it’s also just the easiest to get running for MEGA65 projects.
The LLVM project reinvents the way cross compilers are built: instead of a single compiler dedicated to a single language and target system, LLVM is divided into separate layers for the language, the optimizer, and the target. llvm-mos is a target backend for Commodore computers, and is able to take advantage of a suite of cutting edge tools and language frontends. Because it is based on LLVM, llvm-mos is able to power multiple language compilers, and use the state-of-the-art optimizer from the LLVM core.
The llvm-mos package you just installed includes not only the C compiler called Clang, but also a C++ compiler Clang++. Start writing C++ programs for your MEGA65 today with the mos-mega65-clang++ command!
The clang-tidy command is a tool known as a static analyzer. It can examine your C code, find bugs, and recommend improvements. Programming IDEs like Visual Studio Code can be configured to run such tools automatically to highlight problems as you are coding. Tell VSCode to use the language server included with llvm-mos, called clangd.
You can find all of these and more in the bin/ folder of llvm-mos.
Take everything you’ve just learned about C and throw it in the bin! The new hotness that all the kids are on about is Rust.
Rust is an important new language that intends to be just as powerful as C while making it easier to write programs that are more secure and have fewer bugs. I won’t go into detail on Rust for this Digest—I’m still learning it myself—but I wanted to take a moment to highlight the work wombat has done to bring Rust programming to the MEGA65. See wombat’s MEGAVision talk for a brief video overview.
rust-mos by Mariusz Krynski is a version of the Rust compiler customized for Commodore microcomputers. It requires llvm-mos, with modified installation instructions. Setting up the tool chain is somewhat involved, so read the README file carefully, or consider using a pre-made Docker image if you’re familiar with how to do that. wombat’s mos-hardware is a Rust “crate” with libraries and examples for interfacing with MEGA65 hardware. There’s also a project template: mos-hardware-template.
For learning the Rust language, start with Learn Rust, the official online book and other resources. We’re still figuring out the best way to write Rust programs for the MEGA65, so be sure to join us in the #rust channel on the MEGA65 Discord.
Compared to assembly language, languages like C and Rust provide abstractions that make programs easier to write and understand. They are essential tools for producing large programs whose complexity can be difficult or expensive to manage. Even without perfect compilers that take full advantage of the MEGA65 CPU and memory system, the tools currently available provide plenty of power for MEGA65 development. I still try to write in assembly language occasionally to feel a sense of camaraderie with early programmers that didn’t have these tools, but it’s good to know that they’re just an arm’s reach away.
Happy coding!
— Dan
Cross Development for Fun and Profit, part 1. Dan’s MEGA65 Digest for June 2023.
There’s something wholesome about writing a program on a vintage computer. Such a computer was designed to give equal attention to programs written by their operator and programs written by software companies, and included everything you would need to get started writing such programs. Compared to modern software development, the constraints of on-device retro coding can be comforting and inspiring. When all you have is a Commodore, some graph paper, and a reference manual, you can concentrate on creating programs and solving problems without distraction.
Professional software companies didn’t always do it this way. Larger companies often used other computers to produce Commodore software, such as a mainframe computer with larger storage, computation, and multi-user collaboration capabilities. They would write code using languages like C, and use specialized tools that combined the efforts of programmers and artists into data that could be written to a disk and run on a Commodore. Known as cross development, this workflow gave these companies a competitive advantage: they could work faster, collaborate better, reuse code across projects, and even develop their programs for multiple kinds of computers at the same time.
Today, many hobbyists use modern computers to write programs for vintage machines. There are so many good cross-development tools at our disposal that we can’t cover them all in one Digest. This month, we’ll consider the advantages of cross development, and survey a few tools you can use to write MEGA65 programs in BASIC and assembly language. We’ll highlight recent developments in these tools made specifically for MEGA65 programming. And we’ll introduce an exciting new cross-development language that has just added MEGA65 support: XC=BASIC.
Three quick entertainments in this month’s selections.
Bump Pocket, by MightyAxle.
Bump Pocket, by MightyAxle. Collect colored orbs for points and dodge bombs in this action game, written in BASIC using CBM prg Studio. Use a joystick in port 2.
10 PRINT Racer 80 Column, by JaixBly.
10 PRINT Racer 80 Column by JaixBly. Speed down a path cut through the famous 10 PRINT pattern, in this conversion of a game by Robin of 8-Bit Show and Tell. Press 4 and 6 to move left and right.
MegaPoly, by MirageBD.
MegaPoly, by MirageBD. An homage to the Amiga Boing Ball demo, this modern take renders a smoothly animated rotating 3D shape using the MEGA65’s DMA hardware. Keep this running in the background at your next club meeting!
MEGAVision logo.
Mark your calendars! On Saturday July 1st at 7pm UTC (that’s 12 noon Pacific Time), Gurce is hosting the first ever MEGAVision, an online project share event hosted over Zoom. All topics are welcome, from hardware to software, completed projects or works in progress, or even just personal experiments that you don’t intend to upload to Filehost. And if you can’t make the date, you’re invited to pre-record a presentation to be shown at the event.
Contact Gurce on Discord if you’d like to present something, and keep an eye out on Discord for further instructions. The meeting link will be made available just before the event.
Pacific Commodore Expo Northwest 2023.
If you’ll be near the Pacific Northwest of the United States the weekend of June 24th through 25th, mark your calendars again! Pacific Commodore Expo Northwest 2023 is an annual gathering of Commodore enthusiasts in Seattle, Washington, hosted by Robert Bernardo, the Fresno Commodore User Group, and the Seattle Commodore Computer Club. This year’s venue is the Old Rainier Brewery Intraspace. Attendance is free, no tickets required!
I’ll be at PaCommEx all weekend giving talks and demos of the MEGA65. Challenge me with your toughest questions! If I don’t know the answer, I’ll make something up!
The four-player joystick adapter for the MEGA65, produced by jim_64.
Like other Commodores, the MEGA65 includes two peripheral ports for joysticks and other controllers. That’s fine if you only have one friend, but what if you have more than one friend?
Paul Gardner-Stephens designed a joystick port expansion interface that connects to the expansion (cartridge) port of a MEGA65. Gurce reproduced these results, and if you’re electronics savvy you can make your own.
Thanks to Jim of BIT Zeal (jim_64 on the Discord), you can now buy a pre-assembled four-player joystick interface for the MEGA65. Jim has also put together “Four Fun,” a disk of four-player games that work with the adapter. Jim even includes a disk label for “Four Fun” when you buy the interface.
Four Fun, a disk of four-player games for the MEGA65, compiled by jim_64.
The MEGA65 four-player interface is inspired by a similar Commodore 64 peripheral that connected to the User port. Protovision makes a modern version of this peripheral, but it doesn’t work with the MEGA65 because the MEGA65 does not (yet) have a User port. However, both adapters use the same software interface, so they should be compatible with the same four-player games.
See also Jim’s Filehost page for the adapter for links to all of these resources.
Cross development tools allow you to use a modern computer to develop software for the MEGA65. Typically, you write your code as one or more text files using a modern programmer’s text editor such as Visual Studio Code. You use a tool called a cross compiler to convert your text files into a program that your MEGA65 can run. In cross development terminology, the MEGA65 is the target platform, and the computer you use to develop the software is the host platform.
Typically, the output of a cross compiler targeting Commodore computers is a PRG file. You can put the PRG file on a D81 disk image using a program such as droiD64, which we looked at in a previous issue of the Digest. Copy the D81 disk image to your MEGA65, then use the DLOAD and RUN commands at the READY. prompt to run the program.
It’s possible for a large program to consist of multiple files on one or more disk images. These are typically built with cross development tools to manage all of the code and data, and to create the disk images in an automated workflow. This is an advanced technique and requires specialized code to read from the disks. For this Digest, we’ll focus on single-file programs.
Having a quick and easy way to run code immediately after it is written is essential to the task of programming. This is easy enough if you’re running the software on the same computer where you wrote it: when you want to try your BASIC program, you simply type RUN. For cross development, that last step of getting the PRG to your MEGA65 can be a challenge. Moving the SD card back and forth between your PC and the MEGA65 for each bug fix would drive you crazy. Thankfully, there are other options.
The most common way people cross develop for the MEGA65 is with the Xemu emulator, which runs on your PC. Xemu is like having a MEGA65 on your computer, so you don’t have to transfer your program to another computer to test it. You’ll need a copy of the latest ROM file, and you’ll follow the Xemu MEGA65 Quick Start Guide to set it up.
An easy way to run a MEGA65 PRG file is to drag it into the running Xemu window, then click “Run/inject as PRG” in the dialog window that opens. A faster and nerdier way to run a PRG in Xemu is to start Xemu from the command line, using the -prg command line flag:
I like to automate everything as much as possible, so I make this command part of a build script or shell command sequence so I can build and run my program in a single step. You can also put this along with your build command (such as petcat) in a Visual Studio Code run configuration.
I also like to test my programs on an actual MEGA65 as much as possible. I use a device called a “JTAG adapter” that connects to the MEGA65 mainboard on one end and to my PC via a USB cable on the other. With this connected, I can use a PC app like M65Connect or the m65 command line tool to beam a PRG file directly to the MEGA65. Search for “M65Connect” or “MEGA65 Tools” on Filehost and download these tools for your PC’s operating system. If you want to go this route, see detailed instructions in my MEGA65 Welcome Guide.
We won’t need the JTAG/UART method for much longer. The MEGA65 team has nearly completed a new feature that allows you to transfer files and run programs over the MEGA65’s ethernet jack connected to your local network. This hotly anticipated feature will enable much faster file transfers than a USB serial connection, and won’t require any additional hardware other than a common ethernet cable. Expect ethernet file transfer support later this year.
In a previous issue of the Digest, we introduced two tools for doing cross development of BASIC programs for the MEGA65. One of these is petcat, a command-line tool that takes a text file of BASIC code and produces a PRG file.
Here’s the example we used in the previous issue, a BASIC program that calculates the Celsius value for a temperature in Fahrenheit:
To convert this to a MEGA65 PRG file using petcat, use this shell command:
The command-line tool petcat is included with the VICE suite of Commodore emulators. In late February, the VICE project accepted an update that completes its support for BASIC 65. This update has not yet been included in an official release of VICE. For the convenience of the MEGA65 community, I built the latest version of petcat for each major platform, so you can just download it and use it. Enjoy!
Also remember that there’s a MEGA65 wiki page on petcat that describes how to use it and its text-based syntax.
CBM PRG Studio is a suite of tools for writing programs for Commodore computers with a visual interface for Windows. As we mentioned in a previous Digest, CBM PRG Studio added support for the MEGA65 with its version 4 release. Arthur Jordison continues to add MEGA65 features, and has just released version 4.1.
This new version includes a tool for composing music that can output PLAY commands, as well as a way to export CHARDEF statements from the character glyph editor. Support for BASIC 65 has been improved, and the assembly language workflow uses Kick Assembler for MEGA65 projects.
CBM PRG Studio is an all-in-one cross development suite for Commodore computers, and it’s exciting to see it get more and more useful for MEGA65 programming. If you run Windows on your PC, give the new version a try.
When you save a BASIC program to disk on the MEGA65 using the DSAVE command, it creates a file of type PRG (short for “program”). This file can be loaded back into memory from disk using the DLOAD command. With cross development, you use a tool on a modern computer to produce a PRG file that can be loaded into the memory of a MEGA65.
Consider this simple BASIC program:
Here are the bytes of a PRG file for that program, in hexadecimal:
The PRG file format is very simple: it contains raw data to be written to the MEGA65’s memory, along with the starting address. The address comes first, in Little Endian format (smallest digits first). In the case of a BASIC 65 program, the BASIC program data starts at address $2001, so the first two bytes of a BASIC 65 PRG file are $01 and $20. All remaining bytes are program data stored at that location.
BASIC 65 interprets the data bytes like so:
The DLOAD command makes no effort to validate that the data is a BASIC program or that it starts at a particular address. It just reads the starting address, then loads the data into memory at that address. This means that a PRG file can contain anything intended to be stored in memory. This could be machine code, or data such as graphics and music. You can write a BASIC program that contains DLOAD commands to populate regions of memory from multiple PRG files. Notice that each region must begin in the first 64 kilobytes of memory (with an address between $0000 and $FFFF), because there are only 16 bits (two bytes) for the address in a PRG file.
A common technique for cross development of machine code programs is to produce a PRG file that starts with a short BASIC program followed by the machine code. The BASIC program uses the SYS command to invoke the machine code program at the expected memory location. This allows the user to load everything into memory with a single DLOAD command, then start the program with the RUN command.
Cross development is my favorite way to write assembly language programs for the MEGA65. Assembly language programs can get very long—literally one line of text per instruction—and it can be a big advantage to use modern text editing and source management tools to develop the code. A cross assembler can take 45GS02 assembly language code and produce a machine language PRG file. You can create reusable libraries of routines in files shared across multiple projects, and even write macros that can generate code in useful patterns.
My cross-assembler of choice for MEGA65 coding is the Acme assembler by Marco Baye. I like it because it is fast, featureful, and written in portable C that can be built for any modern platform. It has a traditional assembly language syntax that is easy to learn. Best of all, Acme has native support for the MEGA65 and 45GS02 instructions and mnemonics (such as “LDQ”).
Here is a short Acme assembler source file that generates a BASIC launcher and a two-line machine code program:
You can see that this listing includes more than just the assembly language instructions for the program. It also includes instructions that tell the assembler how to produce the PRG file that we desire. The lines beginning with an exclamation point (!) tell Acme to perform certain actions, such as:
The 45GS02 CPU is exclusive to the MEGA65. It is based on the 65CE02 CPU, a successor to the 65C02 CPU which itself is a descendant of the 6502/6510 CPU we know from earlier Commodores. This means you can use a cross assembler for the 6502 CPU to write MEGA65 software, though you won’t be able to access all of its capabilities. A cross assembler needs to support 65CE02 instructions to access some features, such as the Z and B registers.
The 45GS02’s extensions to the 65CE02 all take the form of combinations of 65CE02 instructions. For example, even though the 45GS02’s “LDQ” is not an instruction of the 65CE02, you can invoke the “LDQ” instruction in a 65CE02 cross assembler with the magic incantation NEG NEG LDA .... See appendices G and H in the Compendium for a complete description of how this works. It’s pretty neat. The Acme assembler knows about 45GS02 instructions like “LDQ” and will generate the appropriate incantations automatically.
Many MEGA65 developers enjoy Kick Assembler. The main release only supports 6502 and 65C02 instructions and not 65CE02 instructions, though this fork by Jesper Balman Gravgaard adds support all the way up to the 45GS02. Kick has a rich feature set for writing and generating structured assembly language code, and is well loved by serious Commodore developers. Shallan’s MEGA65 macro toolkit is written for Kick, which is a strong endorsement. Kick Assembler is written in Java and requires a Java runtime. And don’t miss Kick Assembler 8-Bit Retro Studio, a powerful extension for Visual Studio Code.
Other fine 6502 cross assemblers include dasm, Ophis, and ca65. Note that each assembler has its own syntax, so be sure to read their manuals to figure out how to do things like the BASIC start-up routine. The Acme listing above will only work with Acme.
Want the simplicity of BASIC with the power and speed of machine code? XC=BASIC by Csaba Fekete is a cross-compiled BASIC-like language for Commodore computers. Csaba has just released XC=BASIC version 3.2.0-beta with support for the MEGA65.
Here’s that temperature conversion program written for XC=BASIC:
This example only highlights a couple of features of the language, but they’re worth noticing. For starters, there are no line numbers. XC=BASIC uses named labels and subroutines to indicate how control flows through the program. This program does not make use of labels or subroutines, so it just executes instructions top to bottom.
XC=BASIC variables must be declared before they are used, and the declaration must say what type of value will be stored in the variable. This differs from BASIC 65 (and other Commodore BASICs) that use a symbol like the dollar sign ($) at the end of the name to indicate the value type. In this example, the variables f and c are declared as floating point decimal values. These can contain numbers like 75.4 or -273.15.
The variable fstr is declared as a string, with a maximum length of 20. Unlike Commodore BASIC, strings must have a pre-declared maximum length, so that the memory can be allocated in advance by the compiler. Deciding on a maximum length requires extra effort during programming, but it helps the XC=BASIC compiler produce a faster and more memory-efficient program. This program uses the input statement to accept user input into the reserved string memory, then uses the val() function to convert the string to a floating point for use in the calculation. Also notice that the variable name can be a comfortable length, and is not limited to two letters as in Commodore BASIC.
XC=BASIC is a powerful language with many useful features for structuring and organizing large programs. The XC=BASIC compiler produces a machine code program, so the program runs much faster than BASIC 65, especially with the MEGA65’s 40 MHz processor speed. You can even mix BASIC and assembly language code in the same XC=BASIC program.
The XC=BASIC compiler relies on the dasm assembler mentioned earlier to produce the final PRG. As you get deeper into cross development, you’ll notice that a complete workflow often involves multiple tools, sometimes in a tool chain where the output of one tool is used as the input of another, until the final tool produces a PRG or D81 disk image. In this case, the XC=BASIC compiler generates assembly language code intended for dasm, and dasm produces the PRG. (XC=BASIC invokes the assembler automatically.)
I was able to get XC=BASIC running on my Mac with the following steps:
To compile a program for the MEGA65, invoke the xcbasic3 command with the --target=mega65 option.
I’m as nostalgic for the days of writing programs directly on my Commodore as anyone else, and I still do it sometimes. I use cross development for larger projects for several reasons. On a modern machine, I can type faster, I can save and backup multiple versions of my code more easily, and I can use more powerful tools and languages to write programs. Eventually we’ll have more on-device programming tools like Mega Assembler so I can do more without leaving the comfort of the MEGA65. Both methods have their place.
In next month’s Digest, we’ll continue exploring cross development tools, with a look at programming your MEGA65 using the C language, as well as a language that’s newer than any of our vintage computers, called Rust.
Until then!
— Dan
Bitmap Bonanza! Dan’s MEGA65 Digest for May 2023.
The MEGA65’s VIC-IV video chip has multiple graphics modes. Each mode and feature pulls ideas from some point in vintage computing history: terminal-style text output, character graphics, hardware sprites, palette banks, full-screen scrolling, and even Amiga-style blitter objects and graphics-optimized DMA operations. Several VIC-IV modes are fully backwards compatible with the VIC-II of the Commodore 64 and 128, and the VIC-III of the Commodore 65.
In today’s Digest, we’ll be looking at the VIC-III bitplane graphics mode. While this mode doesn’t show off all of the MEGA65’s capabilities, it’s one of the more fun modes to use with BASIC 65 thanks to its library of 31 drawing commands and functions. In Featured Files, we’ll see a new game that takes advantage of BASIC 65’s graphics system to draw vector art. We’ll also try using a built-in feature to display full-screen high color photographs and illustrations.
This month’s Features Files are all brand new, hot off the presses!
Onion Cake and the Hungry Dinosaurs, by Gurce.
Onion Cake and the Hungry Dinosaurs, by Gurce. This short comedy adventure game combines a text command interface with gorgeous full-screen vector art by Gurce’s sister Ayca and original music. You get to watch the BASIC code fill in the image as it loads each scene, and the code cleverly uses the MEGA65’s memory and DMA features to cache the render so they display instantly on subsequent visits.
Gurce wrote a MEGA65 vector art editing tool, called VART, to develop the image format used by the game. Both the game and the editor are written in the Eleven programming environment.
Onion Cake and the Hungry Dinosaurs is inspired by another MEGA65 game, Escape from Onion Cake by MrZaadii, from his Mega65 Games Pack from 2018. MrZaadii’s game also uses bitplane graphics with pixel art, pre-dating some of the newer graphics features that were added by the MEGA65 team.
Don’t miss Gurce’s behind-the-scenes presentation of the making of Onion Cake.
Old Mine Hoist, by GierS.
Old Mine Hoist by GeirS. This addictive one button game has you lowering a box of supplies down a perilous mine shaft. Struts on the mineshaft walls and barrels of dynamite risk damaging your payload. How far can you get?
Rescue Inc., by SirLazarus.
Rescue Inc. by SirLazarus. An original solitaire strategy game written in BASIC 65. Launch probes to locate missing battleships in the dark ocean waters. Try to find all the ships with as few probes as possible.
Commodore 64 games running on the C64-for-MEGA65 core: Sam’s Journey (left), Rogue 64 (top right), Choplifter (bottom right)
In last November’s Digest we mentioned the Commodore 64 core for the MEGA65 by MJoergen and sy2002, the best way to run Commodore 64 software on MEGA65 hardware. The core completely reconfigures the FPGA for a precise recreation of the Commodore 64 chipset, capable of running software with a very high degree of accuracy and compatibility. The latest stable release is version 4, with support for D64 disk images on the SD card, joystick port peripherals, built-in RAM expansion, and multiple display modes for modern displays.
The C64 for MEGA65 project is ramping up for a major upgrade with release 5. sy2002 has been posting alpha releases to the Discord, and you’re invited to help test! As of V5 alpha 22, the core supports:
As this is an alpha testing release, it comes with a few caveats and has known issues. Be sure to read through the list before installing an alpha release.
For simpler C64 hardware cartridges, you can turn off the MEGA65, connect the cartridge, hold the No Scroll key while turning it on, then select the C64 core from the core selection menu. Remember that if you allow it to boot with the MEGA65 core, it’ll just try to run the cartridge software in its C64 mode, which is not the same as the C64 core and is less likely to be successful. lydon is working on improving the MEGA65 core such that the boot-up process can be configured to automatically select different cores for different types of hardware cartridges.
For EasyFlash and some fancier cartridges, the core selection menu won’t work at all with the cartridge connected. To get this to work, you have to do something we would have considered unthinkable in the days of static-sensitive PLA chips: start with the cartridge not connected, boot with No Scroll, select the C64 core, then connect the cartridge and press the reset button on the side of the machine.
EasyFlash 1 or 1CR works with the latest alpha release. EasyFlash 3 does not yet work. You can buy an EasyFlash 1CR from Daniel Mantione (dmantione in the MEGA65 Discord). Be sure to also order a Protoparts enclosure from Daniel (or from Protoparts directly) to ensure the best fit in the MEGA65 cartridge port.
When using the IEC port with the C64 core to connect disk drives, keep in mind that the C64 core always uses device number 8 for the virtual drive for D64 disk images. Set your external drive to any other device number for use with the C64 core. You can use this set-up to copy D64 disk images to physical floppy disks and vice versa.
Whether you’re installing the C64 core’s latest stable release V4 or trying out the V5 alpha release, the installation process is the same:
If you’re juggling multiple versions of the C64 core, be sure to use the c64mega65 file that comes with that version. This file saves your menu preferences, and the file format has changed between V4 and V5.
Visit the #c64-core channel in the MEGA65 Discord for alpha release downloads, release notes, and troubleshooting issues.
Gurce’s Onion Cake and the Hungry Dinosaurs and MrZaadii’s original Escape from Onion Cake both use the bitmap graphics system built in to BASIC 65. This subsystem allows for rendering high resolution pixel perfect images using BASIC commands. Bitmap graphics are implemented as a separate graphics mode from the text mode you see when writing programs, so you can only see either the text screen or a graphics screen on the display at one time. There are 31 commands and functions you can use to manipulate screens and draw figures in your BASIC programs.
Because the graphics screen hides the text screen, this isn’t easy to experiment with from the READY. prompt. Instead, you can use a short program like this one:
In this example, line 10 opens a new screen that is 320 pixels wide and 200 pixels tall, with a palette of four colors (a “bit depth” of 2). Line 20 sets the color used by subsequent drawing commands (the “pen” color) to palette entry 1 (the second of four colors), in this case using the default palette’s color of white. (See the PALETTE command for a way to change the palette colors.) Line 30 draws a line using the pen color from screen coordinate (25,25) to (295,175), a diagonal stripe.
Line 40 pauses until the user presses a key, and line 50 closes the screen and returns to text mode. This is a useful recipe when you’re experimenting with graphics commands. If your program exits without closing the screen, the MEGA65 will stay in graphics mode and you won’t be able to see the READY. prompt. This can happen if there is an error in your code that stops the program before it closes the screen. If your program appears to get stuck showing a graphics screen, hold Run/Stop and press Restore to reset the display to text mode and a fresh READY. prompt.
The graphics system supports widths of either 320 or 640 pixels, heights of either 200 or 400 pixels, and color bit depths from 1 (two colors on screen at a time) to 8 (256 colors). You can have up to 16 colors (bit depth 4) with a 640x400 screen, and up to 256 colors (bit depth 8) for the other possible resolutions. It is possible to allocate multiple screens and switch between them, though this limits the possible sizes and bit depths due to available memory. Each color palette entry can be any of 4,096 possible colors, with 16 possible values of each of the red, green, and blue components.
It’s worth noting that the MEGA65 video hardware is capable of 24-bit color. The BASIC 65 graphics system only uses a subset of the MEGA65’s graphics capability.
As tempting as it is to tour all 31 commands of the graphics system in this Digest, for now I will leave it to you to discover them in your User’s Guide. Look for SCREEN, BOX, CHAR, CIRCLE, DOT, ELLIPSE, LINE, PAINT, PALETTE, PEN, POLYGON, and SCNCLR, for starters.
BASIC 65 includes a command for saving the currently active bitmap graphics screen to disk. The SAVEIFF command takes a filename, and optional drive and unit numbers. It only works with a graphics screen active, so it’s best to make it part of the program.
The image is saved to disk in the IFF-ILBM file format, a bitmap graphics file format common to Amiga computers. The file appears on the disk as a PRG file, but it’s actually just the IFF-ILBM data, without the two-byte address header of an actual PRG file.
IFF-ILBM files use a simple form of data compression to reduce file sizes. The iamge produced by the program above of a single line on a blank screen at 320x200x2 occupies six blocks on disk to store 1,502 bytes. More complex images, or higher resolutions or color bit depths, will require more space.
A file saved with SAVEIFF can be loaded back to the active graphics screen with another command: LOADIFF. As before, the graphics screen must be active.
Due to how multi-color bitmap graphics are stored, the color bit depth of the active screen must match the file. Loading an image that was saved from a smaller resolution than the active screen (for example, loading a 320x200 image onto a 640x400 screen) will simply load the image into the upper-left corner of the screen, leaving the rest of the screen intact.
SAVEIFF includes the current palette settings with the image data in the IFF-ILBM file. You do not need to restore the palette separately in your program. Notice that the current palette will be overwritten by LOADIFF.
The IFF-ILBM file format is a standard format developed by Electronic Arts in cooperation with Commodore in 1985. IFF, or “Interchange File Format,” is what is known as a container (or “envelope”) format, capable of representing multiple chunks of data of many kinds. Amiga fans mostly know IFF files as still images of the inner format ILBM, or “Interleaved Bitmap.” The IFF-ANIM format was a variant for storing multiple ILBM images as an animation in a single IFF envelope, also popular on the Amiga. As a kid, I only knew that IFF files contained either stills or animations, and you could make them with Deluxe Paint.
Here is the beginning of the IFF-ILBM file created by the BASIC program above, as hexadecimal values:
An IFF file contains one or more chunks. Each chunk has a four-byte type ID and a four-byte size, followed by that many bytes of data. The SAVEIFF command creates a single outer chunk of type FORM, so it begins with those uppercase letters encoded as ASCII (46 4f 52 4d). The size is a signed 32-bit integer in Big Endian format (largest digits first), so 00 00 05 de represents a size of hexadecimal $05de, or 1,502 bytes. It’s not obvious from looking at it, but this is actually a bug in SAVEIFF: the actual data size is 1,494 bytes, but it is erroneously including the eight bytes of the FORM header in this size. Because of this bug, some tools will complain about an “unexpected end of input file” when reading this.
According to the IFF specification, a FORM chunk is a record with an inner type and one or more inner chunks. In this case, the inner type is ILBM, so those are the next four bytes (49 4c 42 4d). The inner chunks have types BMHD, CMAP, and BODY, which are part of the ILBM specification for still images. You can see these identifiers in the hex dump, along with their four-byte sizes and data.
Reading along with the ILBM specification for the $00000014 (20) bytes of the BMHD chunk, we can see the following properties of the image:
The CMAP inner chunk describes the color palette. With a bit depth of 2, there are four possible colors in the image, each described as one byte for each of the red, green, and blue components, $0000000c (12) bytes in total.
The IFF-ILBM format supports RGB component values from 0 to 255 (8 bits). The MEGA65 only supports component values from 0 to 15 (4 bits). LOADIFF uses the most significant four bits of each RGB component value when setting the palette, effectively rounding each number down to the nearest 16.
The spec describes the RLE algorithm that is used for the BODY chunk. For example, $d9 $00 represents forty zeroes, and you can see this repeated in the excerpt above. The decoding algorithm will build out 320x200 bits for each of the four bitplanes. There’s a bit in each bitplane for each pixel of the image. Take the pixel’s bit from each of the bitplanes, starting with the lowest bit in the first bitplane, to get the pixel’s color number.
ILBM is useful for Amiga and MEGA65 BASIC bitmap graphics because these systems represent the screen as bitplanes in memory, so it’s easy to save the image just by compressing memory, and load it again just by decompressing it. The MEGA65 has other graphics modes that don’t use bitplanes.
Most modern graphics software does not support the vintage IFF-ILBM image format. To use an image saved with SAVEIFF, it must be converted to a modern format, such as PNG.
ImageMagick is the ultimate software suite for converting and manipulating image data in a wide variety of formats. It’s free, packed with features, and runs on most operating systems. You typically use ImageMagick from the command line, which makes it great for automation scripts. See the ImageMagick Downloads page for installation instructions for your operating system. On a Mac using Homebrew, install this with: brew install imagemagick
In most cases, you can convert images between formats using the magick convert command:
(If you have an older version of ImageMagick installed, this command is just convert ..., without the magick.)
There’s a slight problem when trying this with files made with the MEGA65’s SAVEIFF command. Those SAVEIFF bugs about the FORM chunk length and 0:0 aspect ratio cause the inner workings of ImageMagick to believe that the conversion failed. When I run the magick convert command on a SAVEIFF file, I get these messages, and no PNG file:
As shown in these messages, ImageMagick delegates IFF-ILBM conversion to a tool called ilbmtoppm, part of another software suite called NetPBM that’s included with ImageMagick. When I run the ilbmtoppm tool directly, it complains about the issues with the file, but successfully converts the IFF-ILBM file to the PPM format:
The PPM format is supported by some modern software, and can be further converted to other formats by ImageMagick.
The PPM file can also be converted back to IFF-ILBM format with the SAVEIFF errors corrected:
You can reverse the conversion process to prepare any image, including high color photographs, as an IFF-ILBM file, so it can be displayed on your MEGA65 with the LOADIFF command in a BASIC program.
For this to work, it needs to not only be in IFF-ILBM format, but also be the right size and color depth for a BASIC 65 screen. You can try adjusting your image to 320x200 and 256 colors (8-bit color) using image editing software, or you can let ImageMagick do it for you.
The latest version of ImageMagick as of this writing (7.1.1) does not appear to recognize the .iff filename extension as IFF-ILBM. Instead, you can conver to IFF-ILBM in two steps, using NetPBM again:
The magick convert command converts photo.jpg to photo.ppm with the following options:
-resize 320x200\! : Resize the image to 320 pixels wide and 200 pixels high. The \! tells ImageMagick to stretch the original image to fit this aspect ratio, which may or may not be what you want. ImageMagick has other options for resizing that can crop or extend the image instead. See any ImageMagick tutorial for examples.
+dither : Disable dithering. Dithering is a technique for representing color and value gradations in digital images, using noise patterns and just a few colors. In this case, we’re converting a JPEG, which may introduce compression artifacts. Disabling dithering prevents these artifacts from being preserved as dithered patterns in the final image. If you’re converting from another format, you may be able to leave dithering enabled.
-colors 256 -depth 8 : Set the color depth to 8, with the maximum of 256 colors.
The ppmtoilbm command needs the -maxplanes 8 argument when the image uses a bit depth larger than 5. For some reason, the command defaults to generating a 24-bit image in these cases unless this argument is specified.
I had some issues with ImageMagick and NetPBM that were resolved by updating to the latest versions. If you already have these tools installed from a while ago, consider updating. With Homebrew: brew update && brew upgrade
In 1985, Jack Haeger created an illustration of a hamburger falling through the air, with a 3-1/2" floppy disk for the hamburger patty. Jack painted the image using an early version of the Graphicraft art software for the Commodore Amiga, one of the first works of art created on the machine. At the time, Graphicraft lacked any way to save an image to disk or export it to print, so Jack photographed the screen with a 35mm film camera. Presumably, Jack eventually turned off the machine, and the digital record of the work was lost forever. The photograph appeared in the Graphicraft manual and the first issue of Amiga World magazine.
In 2023, YouTuber Stuart Brown aka Ahoy recreated “Four-Byte Burger” as digital art. Ahoy described his research and his process in a 30-minute video, including the realization that Jack must have drawn the image sideways then rotated the photograph to give it more height, as shown by the CRT scan lines running up and down the photo. Ahoy concluded that Jack used just fewer than 32 colors, and the original image was 320x200 in size.
Ahoy published a PNG file of his recreation, and by popular demand also produced an IFF-ILBM file of the same image for potential display on an Amiga. Naturally, I wanted to display it on my MEGA65, so I loaded it onto a D81 disk image and wrote an appropriate LOADIFF program, with a screen 320x200x5.
I was a bit surprised that it rendered as mustard and ketchup colored garbage instead of the actual image. So I peeked into the hex dump as we did above. Everything looked as I expected it to, until I got to the compression type field of the BMHD chunk, which was $00 instead of $01. According to the ILBM spec, this indicates that the BODY data uses no compression at all, and not Run-Length Encoding. So I looked at the ROM code for LOADIFF, and sure enough, LOADIFF always assumes the BODY region uses RLE, and ignores the compression type field. (That should be another easy fix in a future version of the ROM.)
There’s an easy workaround: use ilbmtoppm to convert the IFF-ILBM file to PPM, then use ppmtoilbm to convert it right back.
With “Four-Byte Burger,” the resulting file was naturally smaller, and had the compression field set to $01. It loaded fine on the MEGA65. If you have an IFF image file of a compatible size and color depth and it still isn’t loading correctly with LOADIFF, this is an easy workaround to try.
One more tip: If you find an IFF-ILBM file and want to know its dimensions and color depth, use the magick identify command:
Want to display a set of IFF-ILBM images as a slideshow? Check out IFF MegaShow65 by Nobato. This clever program can browse and display multiple IFF image files on a disk. It uses BASIC 65’s graphics system and LOADIFF command behind the scenes, reading the BMHD section of the file to determine the resolution and color depth.
The BASIC graphics system originated at Commodore, and retains a vintage feel. Even though it doesn’t use the MEGA65’s capabilities to their fullest, it’s a ton of fun to play with and use from programs, much easier than using bitmap graphics on a Commodore 64.
Dirty old Onion Cake has kidnapped you. You know that it is your own fault since you have not written enough MEGA65 software. Better get started!
— Dan
Fun with PETSCII! Dan’s MEGA65 Digest for April 2023.
PETSCII is a set of 256 values that can be printed to the screen of a Commodore computer. Most of these codes refer to characters, such as letters, numbers, punctuation, and Commodore’s unique set of graphics glyphs that can be typed from the keyboard. Other codes are control codes that manipulate the state of the screen and printing system, such as to change the color of subsequently printed text. The PETSCII character set is part of what gives Commodore computers their distinctive style. Drawing pictures by typing PETSCII characters and codes is one of the first things everyone does with a Commodore, and there is a long tradition of crafting murals of PETSCII art for demos, games, and computer bulletin boards.
If you’re reading this, you’re probably pretty familiar with the capabilities of PETSCII on a Commodore 64. In this Digest, we’ll review the PETSCII character set, and see how the MEGA65 can learn a trick or two from Commodores that predate the 64. We’ll also take a look at PETSCII control codes that are newer than the C64, and see how we can make special use of PETSCII strings on the MEGA65.
Here’s more stuff you can download and try on your MEGA65 today!
M3wP Solitaire, by M3wP.
M3wP Solitaire by M3wP. Every computer needs some card game fun, and this Solitaire game has it in spades! Connect a mouse to port 1 and play the classic Klondike Solitaire with rich multi-color playing card graphics. You won’t be able to resist just one more hand.
Don’t have a vintage Commodore 1351 mouse or Amiga mouse? Get the mouSTer adapter and connect a modern USB mouse. Make sure the mouse mode is set correctly in the MEGA65 Configuration menu (hold Alt while turning on the computer, then select 1) to match the mouSTer configuration. If you’re one of the lucky ones to receive a modern Amiga Tank Mouse from their Kickstarter campaign, that also works with the MEGA65.
Lemonade for two, by ubik.
Lemonade for two by ubik. An innovative two-player version of the microcomputer classic business strategy game. Use your limited funds to buy supplies based on the weather forecast, sell lemonade in your neighborhood, and leverage your profits into expanding your business. Out-match your opponent and win it all!
Procedurally Drawn Galaxy, by grim_fandango.
Procedurally Drawn Galaxy by grim_fandango. This high resolution graphics demo renders a gorgeous spiral galaxy. Once you’ve admired the image, check out the BASIC program listing to see how it’s done.
The PETSCII text encoding standard was originally invented for the Commodore PET computer in 1977. It uses 8-bit code points for 256 possible values, of which 192 represent typeable characters. Some characters are assigned to multiple code points; the actual number of distinct typeable characters is 128. The remaining 64 code points are used for control codes, or otherwise have no effect when printed to the screen.
While PETSCII was based on the ASCII code standard in use by most computers by that time, the Commodore PET had its own ideas about how to make the best use of the code space. An unexpanded PET did not have a bitmap graphics mode, so PETSCII extended the character set with graphics symbols that could be used to draw boxes, diagrams, and game images. PETSCII actually describes two character sets: one with mixed case letters and some graphics symbols (the “text” character set), and another with only uppercase letters and more graphics symbols (the “graphics” character set). On Commodore machines, the graphics character set is the default. This is why you sometimes see ASCII messages mis-printed on Commodore machines with lowercase letters as uppercase and uppercase letters as graphics symbols. The user can toggle between character sets as needed by pressing the Commodore key and the Shift key together. (This is Mega + Shift on the MEGA65.)
The PETSCII codes for the 128 typeable characters map to screen codes that describe what actually appears on a location on the screen. There’s a second set of screen codes that represent those characters in reverse video mode, for a total of 256 possible screen codes in a character set. With two character sets, the complete definition of a Commodore typeface has 512 possible glyphs, of which only the first 256 or second 256 can be on the screen at one time.
Fun fact: The PET adds a one-pixel vertical space between each line when the display switches to “text” mode, to give it more of an ASCII terminal feel. You can see this in the image above, which I produced in an emulator with a program that prints the PETSCII control code to switch to this mode. (It’s also possible to use the text character set on a PET without the vertical gaps.)
The original Commodore PET typeface was designed with the PET’s built-in monochrome display in mind. These glyphs were used in 40-column and 80-column PET models. The same glyphs were also used in the VIC-20. To reduce costs, the VIC-20 did not have a built-in display and was designed to be connected to the color television set already in your living room. To make the text legible on blurry TVs, the VIC-20 only supported 22 columns of text and stretched the PET glyphs extra wide.
Commodore sought to return to a 40-column text display for the Commodore 64, but there was a problem: the PET glyphs were too thin and spindly to be readable on a TV at narrow character widths. So Commodore redesigned the character set with thicker vertical lines. Nearly every occurrence of a single pixel with space on either side was doubled in some form.
The result is the Commodore typeface we know and love, used unchanged all the way up to the MEGA65. It looks pretty great in 80 columns on a modern display.
The redesign met its goal, but at a cost. Several PET glyphs simply did not survive being made thicker.
For example, the glyph set includes vertical lines of every width on both the left and right side of the tile. Take a look at your MEGA65 keyboard and you can see a few of these are typeable by holding down Mega and pressing keys like L, N, and M. On the PET, CBM+G and CBM+M were vertical lines one pixel wide. Starting with the C64, they are now two pixels wide, redundant with CBM+H and CBM+N, respectively.
Some PET glyphs have been deleted entirely. A fine-grained 1-pixel checkerboard pattern was replaced with a duplicate of the 2-pixel checkerboard pattern. Dotted and line pattern glyphs just became extra empty spaces.
Early MEGA65 contributor Markus Neeb (X2themax on the Discord, aka MPBBS) noticed the missing glyphs. At the MEGA eV open house of August 2022, he proposed a radical idea: restore the missing PET glyphs for the MEGA65. All of the restorations only replace glyphs that are redundant with others elsewhere in the typeface, and because they are both redundant and obscure, they likely haven’t even been used by MEGA65 software. The restored glyphs are authentic to Commodore history, and are demonstrably useful on modern displays in both 40-column and 80-column modes.
It’s intriguing to imagine how re-introducing these glyphs enhances the character of the platform. I know I would have used the fine checker, dotted, and lined pattern tiles all the time if I had them—and a sharp enough display to support them—back in the day.
The MEGA65 Steering Committee decided against modifying the default ROM with these changes, primarily because it’s actually quite easy for any program that wants to use these glyphs to install them. It’s even easier on the MEGA65 than on previous Commodore computers. BASIC programs can just use the CHARDEF command, and machine code programs merely have to write the new glyphs to a memory location.
The following are CHARDEF statements that restore the missing PET glyphs. Feel free to use them in your programs, or in your AUTOBOOT.C65 file.
The ASCII standard includes codes that do something other than print a character when sent to a terminal or teletype. These codes cause the terminal device to perform some other action, such as to move the cursor (or print head) to the beginning of the next line, or signal the operator by ringing a bell.
PETSCII also includes non-printing code points that, when printed, perform an effect, such as:
Control codes can be typed directly into the screen using a key sequence. This is a great way to experiment with control codes and see their effects immediately. For example, hold Ctrl and press 3 to change the printing color to red. Ctrl + 2 changes it back to white. Printing is very similar to typing in this way: it causes the effect of typing each code to occur, in the order the codes appear in the string.
Your User’s Guide has a good reference of PETSCII character and control codes, and their keyboard equivalents, in Appendix B.
The CHR$() function takes a PETSCII code as a number and evaluates to a one-character string for that code. You can concatenate this string with other strings.
The CHR$() function works for all 256 PETSCII codes, but it’s not especially convenient: you have to use a table to look up the control code numbers, and type quite a few characters to spell it all out.
Thankfully, the Commodore screen editor has an alternate way to type control codes into strings just by typing the key sequences that cause their effect. The screen editor knows that you intend to include the code in the string, and not have it take effect immediately, when it is in quote mode. The editor enables quote mode when you type the first double-quote (") character of a string, and disables it when you type the closing double-quote character.
You may have seen vintage magazine program listings represent these typeable codes using labels, like so:
Try typing this command, entering Ctrl+3 for {red} and Ctrl+2 for {white}. They appear as reversed characters inside the string.
Quote mode takes some getting used to. It’s easy to forget that cursor movement keys get quoted, so if you try to cursor left while typing a string, it quotes the cursor-left PETSCII codes instead. A few codes intentionally do not get quoted, such as pressing Return. If you need such a code in a string, the only way is to use the CHR$() function (CHR$(13) for Return).
There is one other way to access quote mode. When you press Shift+INST/DEL, the editor inserts a space at the cursor location and does not move the cursor. It also enters quote mode only for the inserted spaces, so you can type a control code if you need to. This quote mode effect happens even if the cursor is not located inside double-quotes! That’s not particularly useful, but it’s a tradeoff for the fact that the screen editor doesn’t try to understand what you are typing until you press Return.
If you find that you’re in quote mode and you don’t want to be, press Esc then O (the letter O).
It’s useful to know that the screen editor will interpret whatever is on the screen when you press Return, including reversed characters inside double-quotes, no matter how those characters were typed. Technically, you can type a quoted {red} code while not in quote mode by turning on reverse mode and typing the £ (pound) symbol, which is what it would look like if you typed Ctrl+3 while in quote mode. I’ve never done this in regular practice—I typically use the insert method to type quoted codes when modifying an existing line—but it’s fun to know that it works.
Try this:
The Commodore 65 supports text modes for underlining, flashing text, and reverse text. These modes can be combined.
To enable underlining, press Ctrl+B. To enable flashing text, press Ctrl+O. One way to enable reverse text is Ctrl+R, though as we just saw, this is also available as Ctrl+9 aka “Rvs on.” There are PETSCII codes to disable each of these individually, and if you’re just typing them onto the screen you can press Esc then O to disable all three modes. Reverse can also be disabled with Ctrl+0 (zero) aka “Rvs off.”
The printing system keeps track of the text color as its own mode, using that color for printing characters. The blinking cursor is drawn in the current text color. C64 fans know the color changing keys quite well: Ctrl or Mega plus a number key 1 through 8 accesses sixteen colors, as labeled on the number keys themselves. The corresponding PETSCII codes are scattered a bit (white is 5, red is 28, green is 30, etc.), so you’ll just want to look those numbers up in the User’s Guide if you need them.
On the MEGA65, you can access a system palette of 32 colors for text printing. All 32 colors can be used on the same screen simultaneously. To access them using PETSCII control codes, there is a print mode for that: Ctrl+D causes the 16 color codes to refer to colors 0-15, and Ctrl+A causes them to refer to colors 16-31.
Don’t forget that you can change an entry in the 32-color system palette to any of 4,096 colors using the PALETTE COLOR command. You can also change which color is used for printing with the FOREGROUND command (or the COLOR command). See the User’s Guide for more information.
It was very common for Commodore 64 BASIC programs to position text on the screen using PETSCII control codes that move the cursor. To print the message "HELLO WORLD" in the center of the 40x25 screen, a program might print the Home code to move the cursor to the top left corner, followed by 12 cursor-down codes and 14 cursor-left codes, then the message.
BASIC 65 has a dedicated command for positioning the cursor: CURSOR col,row This may be more useful for positioning text on the screen, depending on what you are trying to print.
The terminal display supports tab column positions, similar to ASCII teletypes (and old typewriters). I won’t describe the whole system here. You can experiment with the Tab key (9) and “tab set/clear” (24) code to see what they do.
Pretty much every Commodore 64 BASIC program I ever wrote started by clearing the screen. This felt so powerful, the first step in my program taking control of the machine. The reversed heart character of the quoted clear-screen PETSCII code resonates as nostalgically for me as the blue-bordered home screen.
Press Shift+Clr/Home to clear the screen. Press it in quote mode to insert the PETSCII control code into a string, such that it clears the screen when that part of the string is printed.
As we mentioned last month, the text screen can display either the uppercase character set or the lowercase character set. Each set can have 256 unique glyphs, but only one set can appear on the screen at one time. The default character set keeps uppercase letters and graphics characters in the first set, and lowercase and uppercase letters in the second set.
You can toggle between the two character sets interactively by pressing the Mega and Shift keys together. (Try it!) This toggle effect is not a PETSCII code, and in fact supersedes many program functions so you can do this while a program is running. If your program intentionally uses one set or the other, you can print PETSCII codes to select the set, as well as to disable the Mega+Shift behavior.
Old terminals had a special code that caused a bell to ring, such as to alert an operator at the end of a long job, possibly on a printer in another room. Newer screen terminals support the bell code, mostly using it to indicate an error. The Commodore 65 also has a bell! Press Ctrl+G to hear it.
PETSCII codes 1 through 26 are typeable as Ctrl plus a letter of the alphabet A through Z. Ctrl+S is overridden as an equivalent to No Scroll; code 19 can be entered with the Home key. Ctrl+M is Return, and Ctrl+T is Delete, so these can’t be quoted; use CHR$() for these. As quote mode characters, these codes appear as reversed versions of their corresponding letters. (This pattern extends to other codes and PETSCII characters, though they’re less easy to remember.)
In most cases where a code is usefully paired with another, one code is in the range 0-32 and the other is the same code plus 128 ($80), similar to shifted characters. For example, code 2 enables underlining, and code 130 ($82) disables it. Not every code has a useful pair, and for whatever reason the shift enable and disable codes are simply 11 and 12.
The Commodore 65 assigns several PETSCII codes to keys that have no behavior when printed, such as the function keys. These codes are only useful when reading a keypress with the BASIC GETKEY command. In some of these cases, the corresponding Ctrl keys perform behaviors in the screen editor that do not occur when the code is printed. For example, there is no way to print a PETSCII code with the same effect as typing Ctrl+P.
The screen editor has some advanced features that go beyond the available PETSCII control codes. This extended set is accessible by pressing Esc followed by another key. See the appendix in your User’s Guide for a complete list. (Be sure to download the latest PDFs, which include minor updates to this appendix specifically.)
Only a few escape codes are useful from PRINT. You activate them by printing the PETSCII code for Esc, which is CHR$(27), followed by the appropriate character. As we saw last month, Esc followed by the character 5 switches to 80x50 mode in the latest version of the ROM. You can activate this mode from a BASIC program by printing these codes:
Esc then M disables scrolling of the text display. This can be useful within a program to PRINT on the bottommost line of the screen. Esc then L re-enables scrolling.
Your MEGA65 includes a row of function keys, numbered F1 through F14. The seven keys act as the odd numbers; hold Shift and press one to access the even numbers. Technically, there are sixteen function keys, with the last two being the Help key and the Run key, respectively. (Press Shift + Run/Stop to act as Run.)
By now, you or your cat may have pressed these keys in the BASIC editor and noticed that they do various things. Some are super useful, and others are not obviously helpful. I know I’ve tried pressing the Help key on a Commodore 128, only to be disappointed that it just shouts HELP back at me and doesn’t appear to do anything else.
In the BASIC editor, the purpose of the function keys is to type strings of PETSCII codes. These strings are programmable! When you press a function key, it types its string as if you typed it out manually. For example, the default definition of the Help key is a string of five codes: HELP followed by the Return key. On a blank line, this enters the BASIC command HELP, which displays information about the most recent error encountered by your BASIC program. (If your program didn’t recently encounter an error, the HELP command prints nothing.)
To see a list of all of the function key definitions, type the KEY command:
Knowing what we know about PETSCII codes, we can see how the default definitions of the function keys work. Several definitions use CHR$(27) to refer to the Esc key, entering escape codes. Others use CHR$(13) to type the Return key to enter commands. Some definitions use quoted control codes to type the equivalent key sequences.
Notice that key sequences that control the BASIC editor don’t work with the PRINT command, but they do work in function key definitions. For example, function key F9 is defined as a synonym for Ctrl + P, which scrolls a line of a BASIC program listing onto the screen from the bottom. Paired with the default definition of F11, Ctrl + V, these keys are a handy way to browse a BASIC program listing, and more convenient than using the control sequences directly.
To redefine a function key, use the KEY command with arguments: the function key number, a comma, and the string definition. For your convenience, this is how the KEY command displays the current definitions, so you can cursor up to one of those lines, make a change, and press Return to register the new definition.
It can be really handy to define function keys for project-specific tasks. For example, say you’re troubleshooting a subroutine on line 3500 that has different behaviors depending on the value of the X variable, and you want to try it with different values. You can define the function keys F1 and F3 as follows:
Now you can test the subroutine quickly: press F1, enter a value for X, then press F3.
Once you have function key settings that you like, you can save them to a file on disk, then load them again later. These commands are KEY SAVE "filename" and KEY LOAD "filename", respectively. Save your project-specific definitions on disk with your other project files. You can even have multiple definition files and load them as needed.
In the December 2022 issue of the Digest, I mentioned a handy tool for developing MEGA65 BASIC programs on your PC called petcat. This tool is distributed with the VICE suite of Commodore emulators. It converts between PETSCII characters and an ASCII text-based syntax, so your programs can include all of the possible characters even though your PC doesn’t have a Commodore keyboard.
For the more unusual PETSCII characters and control codes, petcat has a label syntax using curly brackets, similar to what we used earlier for codes like {red}. You can type these labels directly into your text file, and petcat will generate the equivalent PETSCII code when it makes the PRG file.
To my knowledge, there isn’t an existing prose document that describes all of the petcat syntax. So I wrote one. See my new petcat syntax reference in the MEGA65 Wiki. Feedback welcome!
PETSCII is a defining feature of Commodore computers, providing a ton of display power that’s easy to use in BASIC programs. I hope it inspires you to do something great!
Cheers!
— Dan
A Rorschach Test on Fire. Dan’s MEGA65 Digest for March 2023.
This month, we have featured files, featured features, new hardware, and a classic programming exercise to play with. Let’s get started!
Get this month’s Featured Files from Filehost and keep them on your SD card for showing off to your friends!
LUMA by Shallan50k. Shift the components around on a playfield to fire lasers at targets. Use a joystick in port 2: select a piece, hold the button, then push it in a direction. Try to solve each puzzle in as few moves as possible.
Wave Hero by GeirS. A watersports-themed one-button runner with smooth gameplay, a gorgeous color palette, and authentic SID sounds. Use just the button of a joystick in port 2. This adaptation of a C64 game includes source code written in Millfork.
Mandelbrot Explorer 65 by lydon, with assembly source. The fractal so famous there’s a song about it. See also Mega-Mandelbrot by Liquidream, in BASIC.
In addition to the 3-1/2" floppy disk drive built into the MEGA65, the computer supports connecting a vintage Commodore 1581 external floppy drive to the IEC port. These drives are difficult to obtain, with working units listing for upwards of $400 USD on eBay. If you want a second drive for your MEGA65, there’s a new option!
Foenix Retro Systems is taking pre-orders for a new Commodore-compatible 3-1/2" floppy drive, the FNX1591. Like the 1581, it supports double-density (DD) disks, for 720KB of storage per disk. The FNX’s firmware can be updated over USB, and it can store multiple firmware options that can be selected by a switch. Another switch can set the IEC unit number. The drive uses a modern power supply and power switch, and sports two IEC connectors for daisy-chaining devices.
The FNX1591 is intended to be compatible with all computers that work with the 1581, including the MEGA65. You can preorder one today for $275 USD + $45 USD flat rate shipping. Delivery is estimated for April 2023.
The drive’s resin-printed case is designed to match the Foenix F256K, an all-new 65C02-based wedge-style computer. The F256K is not currently open for orders, but the F256 Jr, a low-cost bare-board version, is for sale for only $199 USD. If your MEGA65 needs a friend, you can’t go wrong with an F256 Jr.
Sew Ready, a maker of boutique dust covers for vintage Commodore equipment out of Norfolk, United Kingdom, now offers an embroidered dust cover for the MEGA65! Grey with stylish red piping and a rainbow “65” logo, this cover protects your MEGA65 (or your Commodore 65, if you have one) while leaving the ports exposed, so you can keep it connected and covered at the same time. £22.99 plus shipping. While you’re there, get matching covers for all your Commodore gear.
Looking for other dust cover options? Some large-size keyboard covers like this one tend to fit the MEGA65, and the cheap ones are practical. I found a generic stretchy keyboard cover that just fits, though it won’t protect it from things set on top of it or cats walking across it. For something more durable, lydon found this acrylic keyboard cover that is sized correctly, and works well with these clear elastic buffers. Others have found acrylic display stands that, with the right dimensions, can do the trick and look pretty stylish.
Want to mount your MEGA65 to the wall? 8-Bit Resurgence (COREi64 in the Discord) made a video on making 3D-printed presentation brackets.
As I mentioned last month, the MEGA65 ROM is getting new updates. February saw a series of updates that promoted features that were contributed over the last year, using a new testing process to eliminate bugs and confirm backwards compatibility with existing MEGA65 software. See the ROM FAQ for a reminder on how to obtain and install the latest beta release.
The following new features have been added to beta releases since the last release package, up to the most recent ROM version as of this writing, ROM 920383. Many thanks to Bit Shifter for these contributions, and for all of his work on the ROM over the years!
The MEGA65 operating environment starts up in a text mode with 80 columns and 25 rows. You can change the environment’s display mode to 40 columns and 25 rows by pressing the Esc key followed by the 4 key. To switch back to 80x25, press Esc then 8.
Starting with ROM 920382, you can switch the operating environment to 80 columns and 50 rows, plenty of screen space for BASIC program code and directory listings. To switch to this mode, press Esc then 5.
Be advised that some software might not run correctly if started with the computer in a state other than the default boot state. Technically, this is true for anything you can change about the state of the computer, and is not particular to the new 80x50 mode. Some programs would also be confused if you start them in 40x25 mode. When writing a program, it’s best to not assume any undocumented default state: either test the state, or set it to be as you need it.
To set the text screen mode from a BASIC program, use the PRINT command to emit the PETSCII codes for Esc (27) and the appropriate number character. You’ll probably want to also emit the code to clear the screen (147).
BASIC 65 has built-in support for the mouse. When you enable the mouse with MOUSE ON, BASIC 65 uses the first sprite of its sprite system (sprite 0) as a mouse cursor. In previous versions of the ROM, the BASIC program had to provide its own sprite image for the cursor. You can still provide a custom image, but now you don’t have to: the default image for sprite 0 is an arrow-shaped mouse cursor.
If you have a compatible mouse (or a modern USB mouse and the amazing mouSTer adapter), try this command to see the BASIC mouse pointer in action:
In a BASIC program, you can read the position and button state of the mouse into variables using the RMOUSE command. See your User’s Guide for more information.
In addition to the mouse sprite, the other seven sprites are now set a simple default pattern, so you can experiment with the BASIC sprite system without first loading image data.
The CHARDEF command in BASIC 65 can replace the glyph of a screen code with a custom pattern. (We played with CHARDEF a bit in the September 2022 issue of the Digest.) In previous versions of the ROM, CHARDEF could only modify the first 256 screen codes in the uppercase character set. Now you can use CHARDEF with all 512 screen codes, numbered 0 through 511.
Remember that your program can only display either the uppercase character set or the lowercase character set on the screen at one time. To switch to the lowercase set, PRINT PETSCII code 14:
Surprisingly, there is no PETSCII code to switch back to the uppercase character set. [Update: Thanks to Rhialto for the correction:] To switch back to the uppercase (“graphics”) set:
You can also use the VIC register at $D018 (53272) to switch between uppercase and lowercase. For the default character set on the Commodore 65, the lower four bits should be 4 for uppercase, or 6 for lowercase.
If your program depends on the character set not changing, you may want to disable the ability for the user to toggle between the two sets by pressing Mega+Shift. Print PETSCII code 8 to disable it (and PETSCII code 9 to re-enable).
In last month’s Digest we explored the MEGA65 Monitor as an essential tool for learning machine language, understanding how the computer works, and troubleshooting machine language programs. With the latest ROM, the Monitor just got even more useful.
We saw how you can start the Monitor by typing the MONITOR command at the READY. prompt. The MEGA65 will also activate the Monitor when a machine language program executes the BRK instruction. This is super handy for investigating a problem with the state of the computer from inside your program: just add a BRK instruction and run your program, and it’ll stop at exactly that spot and open the Monitor so you can inspect registers and memory.
With the latest ROM, the Monitor has been improved so it knows exactly where the BRK instruction left off. You can now continue your program from the Monitor using the G command without arguments, assuming you did not modify the program counter while you were in the Monitor.
Anyone who has written a machine language program knows how it feels when a bug in the program causes it to get stuck, ignoring all input, appearing to do nothing—or worse. For these cases, Commodore provided us an escape hatch: hold Run/Stop and press Restore. This triggers an interrupt that tells the CPU to stop what it’s doing and hand control to the kernel.
Traditionally, the kernel would handle this interrupt by clearing the screen and displaying a READY. prompt. This isn’t particularly useful when troubleshooting a machine language program. The latest ROM does something a bit smarter: it opens the Monitor, with the program counter set to wherever you interrupted it, as if there had been a BRK instruction at that location. In many cases, you can even resume your ML program after interruption, using the G command!
With the new ROM installed, try assembling the infinite border color program from last month’s Digest, then execute it to enter an infinite loop. Press Run/Stop+Restore to break into the Monitor. Then enter the G command to resume the fireworks.
Rendering the Mandelbrot set is a rite of passage coding exercise, similar to implementing Conway’s Game of Life. lydon’s Mandelbrot Explorer 65 and Liquidream’s Mega-Mandelbrot show off the MEGA65’s color bitmap graphics capabilities. To celebrate the launch of 80x50 BASIC text mode, let’s try a low-res version!
The Mandelbrot set is the set of complex numbers c for which the function f(z+1) = f(z)^2 + c does not diverge to infinity when iterated from z = 0. In other words, take a complex number c, then starting from zero, repeatedly add the complex number and square the result. If the results run off to infinity, the number c is not in the set. If the results never run off—maybe they bounce around locally or converge toward zero—then c is in the set.
The most famous image of the Mandelbrot set represents the points on the complex plane where c = x + iy, where i is the imaginary constant defined as i^2 = -1, centered on the origin (0, 0) and zoomed in fairly close. Points that are in the set appear in the image as black, forming bulbous round shapes.
A simple computer program can draw the image as a bitmap by testing every pixel (x, y) as a coordinate on the complex plane, starting the function at the point and iterating until either it starts to look like the value is diverging, or a maximum number of iterations is reached. If the value is still near the starting point after the maximum iterations, the program concludes it is in the set. Traditionally, the program assigns diverging (non-member) points a color based on the number of iterations it took to detect divergence, giving the figure a glowing effect that shows how points near members of the set take longer to diverge than those farther away.
(See also Dr. Holly Krieger’s excellent explanation in The Mandelbrot Set episode of Numberphile.)
Let’s write a BASIC program to draw this using 80x50 text mode. First, adjust the color palette to provide a gradient of colors for the non-set points. You can experiment with different values to adjust the colors to your taste.
A BASIC program can set the screen mode by printing the PETSCII code for the ESC key (27) then the character for 5, similar to if you typed it.
To draw the pattern, the program visits each character position once, using a nested FOR loop. For this program, we’ll set every character on the screen to a solid rectangle, then set the color based on our calculations. The BASIC 65 special array T@&() gives us access to the characters on the screen, and the special array C@&() gives us access to the colors. These arrays are indexed with a row and column number, and you can read or assign to these values, similar to other arrays.
The program fills the screen with solid rectangles (screen code 160). The rest of the code will test the point for set membership and set its color accordingly.
The first thing we need to do is determine the actual x/y coordinates on the complex plane for each position on the screen. The y-axis should be in the center, so the x coordinate is 0 when the column number K is 40. Similarly, the x-axis should also be centered, so the y coordinate is 0 when the row number R is 25. We also need to scale down the coordinate ranges to be much smaller, so we can see something interesting. These calculations for X and Y should produce interesting results:
These variables represent the complex number c = x + iy that corresponds with the coordinate on the screen. We need to keep track of the iteration value, a complex value stored in the variables ZX and ZY. We also need to keep track of the number of iterations, in variable N. Initialize these variables to zero.
BASIC 65 does not have built-in support for complex numbers or the imaginary constant i, but it turns out we don’t need it. We can calculate the new values of ZX and ZY using separate equations for the real and imaginary parts. Remembering that i squared is -1, the square of a complex number can be figured as follows:
To complete the equation, add the components of the original complex value, X and Y. The complete BASIC code for updating the ZX and ZY variables is as follows:
Each time we iterate this function, we can determine whether the function is diverging by testing whether the updated point is far away from where it started. We’re using starting points that are very close to the origin, so to keep the math simple, we can take the distance of the new point from the origin. This distance, known as the magnitude of the complex number c = x + iy, can be found using the Pythagorean Theorem, the square root of the quantity x^2 + y^2.
In BASIC 65, the square root function is spelled SQR(), so we get our magnitude like so:
We’ve just completed an iteration, so we need to increment the iteration counter N:
Now we can test whether we’re done iterating. If the magnitude of the value hasn’t gotten large enough to conclude that the function is diverging, and we haven’t yet reached the maximum number of iterations, we continue iterating.
After iteration is complete, we determine the color of the screen location based on the number of iterations. If we hit the maximum, we conclude that the point is in the Mandelbrot set, so the square should be black. Otherwise it is some other color based on the number of iterations. With a maximum iteration count of 80, one way to convert this to a color value between 0 and 15 is to divide it by 5.
That’s it! RUN this program and watch it draw a pattern that roughly resembles the Mandelbrot Set image. 80x50 is a low resolution, but it’s close to the first picture of the Mandelbrot Set, published by Robert W. Brooks and Peter Matelski in 1978.
Mandelbrot Set, you’re a Rorschach Test on fire
Peace and love,
— Dan
What I Wish I Knew About Machine Language. Dan’s MEGA65 Digest for February 2023.
I spent six years of my early childhood on my Commodore 64, between ages 6 and 12. I wrote many programs, all using the built-in BASIC language, learning everything I could from reading the Commodore 64 Programmer’s Reference Guide and typing in program listings from Compute!’s Gazette magazine. I learned a lot from writing BASIC programs, but the one lesson I took away over and over again was this: to make anything really cool, like Marble Madness or Skyfox, I’d need to know machine language.
Machine language felt like dark magic. In Compute!’s Gazette, all the games with the cool graphics and high speed action were printed as columns of numbers, a pages-long incantation that if you typed it correctly would conjure a video game. The Programmer’s Reference had a chapter on machine language that I stared at endlessly trying to make sense of it, but it only made a passing reference to the fact that I needed additional software to write it. If I were older or had a friend with more experience, I would have known what utility cartridge to ask my parents for as a birthday gift, but it was too much for my kid self to figure out all by myself in a basement.
In fairness, Compute!’s Gazette did publish the occasional machine language coding tool, like Fast Assembler in the January 1986 issue. The companion disk to the issue even included the source code for Fast Assembler itself, the first time I had ever seen a complete machine language program listing. I remember making a small change and running the assembler on its own code, which produced a new version of the assembler that printed my name instead of its own. But that’s as far as I got.
In this issue of the Digest, we’re going to answer the questions I had when I was a kid. What is machine language? What is an assembler? And what in the name of Chuck E. Cheese is hexadecimal? We’ll also look at ways you can start learning machine language right now with your MEGA65.
It’s time once again for Featured Files, where we highlight stuff you can download from the Filehost and try with your MEGA65 today!
Mega Wizards, by RBJeffrey.
Mega Wizards, by RBJeffrey. A game for one to four players, using the joysticks. Use your wizardly wiles to bounce the magic ball, take out your enemies, and defend your crystal. Three and four players require a four-player joystick interface.
WORDUP, by geehaf
WORDUP by geehaf. A faithful variant of the popular daily word game Wordle, playable on your MEGA65. Guess the secret five-letter word in six or fewer tries, using hints produced by each guess.
xmas65, by MirageBD
xmas65 by MirageBD. A holiday greeting for the MEGA65 community with an impressive graphical effect and a rockin’ MOD-style backing track.
Intro Disk #02, a collection of software for the MEGA65.
The intro disk is the first thing you see when you turn on the MEGA65 for the first time, a bundle of games, demos, and music ready to play and show off your new computer to your friends. Thanks to Gurce, there’s now a second intro collection for your enjoyment!
Intro Disk #02 goes beyond the bounds of a single D81 disk image with dozens of titles and music files, all browsable from a colorful menu. Unpack the zip file and copy the files to your SD card, then boot the INTRO2.D81 disk image.
There are a lot of files for this one. I had success keeping the files in a subfolder on the SD card. You may want to move the MODS/ subfolder to the root to make these music files easier to play with the new version of the Manche MOD player, included on the intro disk.
The original C65 prototype ROM chip.
The MEGA65 ROM is the built-in program code that powers the kernel, the BASIC programming language, and the operating environment. It’s what Commodore would have burned into a physical ROM chip had they released the Commodore 65 as a product. In the case of the MEGA65, the ROM is actually a file on the SD card, loaded during boot by the firmware.
Commodore canceled the C65 project before finishing the original C65 ROM. The MEGA65 team has made significant investments into finishing planned features, fixing bugs, and generally making improvements in the spirit of the original Commodore design. The latest MEGA65 ROM is much more useful thanks to these efforts. Release package version 0.9, which shipped with the first batch of MEGA65s in May of last year, bundled the ROM with the version ID of 920287. The most recent release package as of this writing is version 0.95, which shipped with the second batch last October, with ROM 920377.
The work continues on improving all aspects of the MEGA65 platform, including the ROM. You are invited to help test new “beta” releases of the ROM, starting with version 920378, now available. If you own a MEGA65 and are signed in to Filehost with your account, you can download the latest beta ROM and install it on your SD card. If you do not own a MEGA65, you can put the ROM together for use with the Xemu MEGA65 emulator, using the original C65 ROM, the MEGA65 ROM patch file, and the M65Connect app (also available on Filehost). (The C65 ROM is available for free for personal use as part of C64 Forever Free Express Edition from Cloanto.)
If you discover an issue with any version of the ROM, please report it using the Issues tab of the mega65-rom-public Github repo. Check out the new MEGA65 ROM FAQ article with answers to common questions and instructions on how to download and use the latest ROM. Also, be sure to join the #closed-roms channel on the Discord for updates.
One of the first things I learned to do with the Commodore 64 was this command:
This command still works today on your MEGA65. (Try it!) If you haven’t memorized what these numbers mean, it’s difficult to tell what this command does just from looking at it. Newer Commodores added an equivalent BASIC command that better describes its function, also available on the MEGA65:
The POKE command takes two numbers: an address and a value. It instructs the CPU to send the value to whatever device inside the computer is wired to that address. The effect this has depends entirely on what’s there. In the case of 53280, the address is connected to the VIC video chip, specifically the part that controls the color of the screen border. The different values represent different colors.
In many cases, the device at an address remembers the last sent value, and the CPU can retrieve it with another command:
The POKE command and PEEK() function are most often associated with computer memory, a device whose sole purpose is to remember the most recent value sent to an address for as long as the computer is powered on. Here’s an address on the MEGA65 connected to memory:
Most addresses are connected to memory chips. Some are connected to other devices, like video and sound generators, disk drives, the keyboard, joysticks, and so on. Non-memory addresses are known as registers, or more specifically I/O registers for their purpose of reading input from and writing output to the devices that live there. Not all registers accept new values. For example, the CPU can read a register connected to a joystick port to see which way the joystick is being pushed, but there is no way to send a value to the joystick.
There are 256 possible values you can send to or read from an address, numbered 0 to 255. The meaning of the value depends entirely on how it is used. It can be a color, a character of text, a set of pixels on the screen, the pitch or volume of a sound, a piece of a larger number, or anything else that can be represented by a value.
Internally, the computer represents a value as one or more digital electronic signals. This fundamental unit of digital data is known as a bit, with two possible values, typically represented by the numbers 0 and 1. Bits can be combined to represent more possible values: two bits can represent four values, 00, 01, 10, or 11; three bits can represent eight values. The value you send to or read from an address is eight bits, also known as a byte, with 256 possible values. The MEGA65 CPU mostly deals with byte-sized values, which is why it’s called an “8-bit computer.”
It’s very common to describe bit patterns as numbers—specifically, integers counting up from 0—even when they don’t represent numbers in the data. The binary number system puts these bit patterns in order. The first six binary numbers are 0, 1, 10, 11, 100, and 101, equal to the decimal numbers 0 through 5.
Just as decimal place values are powers of ten (1, 10, 100, 1000), each binary place value is a power of two (1, 2, 4, 8). You can convert a decimal number to its binary equivalent by setting the bits whose place values add to the number to 1. To convert from binary to decimal, add the place values where bits are set.
Addresses are numbered starting from 0 and counting up, and it should be no surprise that the computer uses bits to represent addresses. A Commodore 64 uses 16 bits (two bytes) for addresses, for 65,536 possible addresses. The MEGA65 uses 28 bits for addresses.
Because the MEGA65’s 45GS02 CPU is an evolution of the Commodore 64’s 6510 CPU, MEGA65 machine language programs mostly work with 16 address bits, and use other features of the 45GS02 CPU to complete the address. It’s kind of like telling a taxi driver where to go using just the house number and street name, and assuming the driver knows the city, state, and country. See the chapter on memory in the manual for more information about how this works.
We use decimal numbers in our daily lives, but it gets unwieldy when working with computer programs. Computers are designed around binary, so all of the useful value ranges are convenient in binary—and confusing in decimal. 255 feels like a weird stopping point for a byte, but in binary it’s just the largest eight-digit value: 11111111. As more bits get involved, the possibilities get even more difficult to track. Why is 65,536 an important number? How much is 1,048,576? What is at address 268,251,168?
Writing programs using binary numbers would quickly drive us mad. A 28-bit address would literally be twenty-eight 1’s and 0’s. We need a concise way to represent these numbers that doesn’t make them more confusing. That’s where hexadecimal comes in.
Hexadecimal is a numbering system that uses sixteen possible values per digit, so a single hex digit completely represents all possible values of four bits. A byte value can be represented by two hex digits instead of eight binary digits.
Earlier we saw that the border color address is 53280 in decimal. It looks like a random number, if you haven’t memorized it. In binary, a hint of a pattern emerges, but it’s still difficult to manage: 1101000000100000 To convert this to hexadecimal, split the bits into four-bit groups, then find the hex digit that represents each group. 53,280 in hexadecimal is D020.
To avoid confusing a hex number with a decimal number, it is often written with a dollar sign in front: $D020. This convention is common to microcomputer programming. (Modern languages use different conventions for hex numbers, such as 0xd020 in Python.)
Commodore 64 BASIC only knows decimal notation for numbers, so C64 programmers are well practiced at converting between bit values and decimal notation. MEGA65 BASIC can handle hexadecimal numbers directly, so you don’t need to bother. Just use the dollar sign notation:
This makes it easy to use MEGA65 BASIC as a hexadecimal calculator. To convert a hexadecimal number to decimal, simply print the value:
To see the hexadecimal representation of any number or expression, use the HEX$() function:
The MEGA65 I/O registers are in the address range $D000 – $DFFF. In hexadecimal, all of these addresses start with a D. This is easier to understand than using decimal notation for the range: 53248 – 57343.
Most books on this subject discuss at length how to convert between hexadecimal and decimal. This is fine for getting accustomed to the idea. In practice, as long as your programming tools support hexadecimal notation, you rarely need to convert between hexadecimal and decimal. It’s more convenient to leave addresses and values in hexadecimal, and understand how hex digits represent bit patterns in groups of four. Adding one hexadecimal number to another takes some practice—but you always have your handy MEGA65 to help you.
The CPU’s job is to perform the instructions of a machine language program. When it’s not running the instructions of your program, it is running the instructions of the MEGA65 kernel to blink the cursor, perform BASIC commands, access disk drives, and so forth. If it doesn’t look busy, it’s busy waiting.
Machine language instructions manipulate memory, interact with I/O registers, perform simple calculations, and make decisions about what instructions to perform next. There are surprisingly few things the CPU knows how to do. Most of its power comes from being able to perform very many instructions very quickly.
The CPU reads its instructions from bytes in memory. It keeps track of which address has its next instruction using an internal register called the program counter (PC). The CPU reads the instruction from the address stored in the program counter, then does it. By the end of the instruction, the program counter contains the address of the next instruction to perform, and the process repeats.
Those columns of numbers in a Compute!’s Gazette magazine program listing are machine language instructions (and data) for the program. As you type them in, Compute!’s “MLX” data entry program stores those values at their corresponding addresses. (MLX magazine listings also include a checksum value as the last number in the line, so it can catch your typing mistakes.)
To start a typical Compute!’s Gazette program, you use the BASIC SYS command with the address of the first instruction. SYS sets the CPU’s program counter to that address, and the program takes it from there.
You can write your own machine language routine in a similar way, setting values in memory that represent instructions then calling the routine with SYS. Try entering these commands on your MEGA65:
If you mis-type any of these numbers, your computer might do something strange. You can always restart the computer and try again.
Yes, EE 20 D0 60 is a machine language program. You’re not expected to know what it means, nor are you expected to write programs that way. It’s possible to do so, in the same way that I used to sit in that basement drawing pixel art on graph paper and converting it to byte values for my DATA statements, but it’s slow going. (I tried this recently as an exercise for a different microcomputer. It’s fun, the first time.)
When most people say they’re writing a machine language program, most often they’re actually using assembly language, a programming language that is roughly similar to the computer’s machine language, along with a tool that converts it to machine code called an assembler. Assembly language consists of the same instructions that the CPU knows how to perform, just spelled out in a way that’s easier to read and write.
Here’s that short machine language routine again, this time written as assembly language instructions:
The first instruction tells the CPU to increase the value at address $D020 by one. The second instruction returns from the subroutine. As we’ve seen, address $D020 controls the border color. Each time you SYS to the first instruction, the border color changes, and control returns back to BASIC.
The CPU contains a little bit of memory of its own to use as scratch paper while performing computations. The MEGA65’s 45GS02 CPU has four general purpose registers, each the size of a byte: an accumulator (often referred to as just A), and registers X, Y, and Z. The program counter (PC) is an example of a special purpose register, holding the address of the current instruction.
The CPU maintains eight one-bit registers, called flags or just status registers (SR), that indicate useful aspects of the machine’s operation. For example, the Zero flag is set after a math operation results in zero, which is useful for countdowns or comparing whether two numbers are equal.
The CPU reserves a small area of memory to use as a data structure called a stack. Much like a stack of cards, you can push new values onto the stack, and pull the last pushed value off of it. The CPU uses the stack to remember its place when calling a subroutine, like the SYS command does, so it can return to that place when the subroutine performs the RTS instruction.
The CPU gives special treatment to a single page of memory, 256 bytes starting at an address that ends in $00. It can access this memory faster than other locations, so it’s useful for storing variables that change frequently. In the Commodore 64 (and the 6502/6510 CPU), this is known as the zero page because it is always located at address $0000. In the MEGA65, the 45GS02 CPU can change which page it uses for this purpose, so it is known as the base page. The location of the base page is stored in a register (B).
Nearly all CPU instructions manipulate a value in working memory, a value at an address, or both. Here are just a few examples:
Instructions that access addresses often have variants for different addressing modes that describe how the address is calculated. As shown in the examples above, some instructions can read a value from an address provided with the instruction, or it can read the value provided with the instruction itself (which is just reading it from the memory that contains the program code).
Addressing modes are a powerful concept, and understanding them is critical for performing certain tasks effectively. The MEGA65 45GS02 CPU has many addressing modes. I recommend learning a few common ones to get started, then read about the rest once you’ve tried writing a few short programs.
The MEGA65 manuals describe the 45GS02 instruction set and addressing modes in detail. The 45GS02 supports all of the instructions of the 6502, so descriptions of the 6502 instruction set (another good one) that you can find online and in books also apply to the MEGA65.
The chapter on machine language in The Commodore 64 Programmer’s Guide makes a brief mention of a software tool called “64MON,” and uses it to introduce machine language concepts. I know they did not intend this to be cruel, but it was an insurmountable hurdle for me as a kid that Commodore did not include 64MON or anything like it with the computer.
64MON was a machine language monitor, a tool for examining and interacting directly with the CPU and memory of a microcomputer. An ML monitor is a gateway to accessing the raw power of a machine, so useful that many microcomputers had one built in. The earliest models of the Apple II even booted directly into an ML monitor, instead of BASIC. Commodore added a built-in monitor to their computers starting with the C16. The MEGA65 includes an all-new monitor, written by Bit Shifter.
To start the MEGA65 ML monitor from the READY. prompt, type the MONITOR command:
The monitor accepts commands similar to the BASIC environment. For example, to exit back to BASIC, type X then press Return. The monitor uses the BASIC screen editor, so you can cursor up to previous lines to repeat or modify commands.
The first thing the monitor displays is the contents of the CPU’s working memory: the program counter, the status register, the accumulator, and so on. These values aren’t useful when the monitor first starts with the MONITOR command, but you can examine them at any time with the R command.
I won’t describe all of the monitor’s uses and features here, but I do want to mention two of its primary functions: examining and changing memory values, and assembling and disassembling machine language instructions.
Try this command:
The M command takes an address in hexadecimal (with or without the $), then displays a block of memory values in hexadecimal. If you POKE’d that short program into memory earlier, you’ll see the byte values at the beginning of this list, along with a bunch of junk values:
The command to change values in memory is the > that appears at the beginning of one of these lines. This is not a coincidence: you can move the cursor up to any line printed by the M command, change a value, then press Return to modify the memory.
The monitor knows how to assemble instructions directly into memory, using their assembly language mnemonics. To start the assembly process, use the A command followed by a starting address and the first instruction, then press Return. It converts the assembly instruction to machine code, stores it in memory, then prompts for the next instruction. Press Return without an instruction to end assembly.
Try typing A 1800 INC $D020, followed by Return. Then enter RTS on the next line, and finally enter a blank line. Notice that the assembler displays the machine code byte values that it came up with as you type: EE 20 D0 are the bytes for INC $D020, and the 60 byte means RTS.
To see the assembly instructions stored at an address, use the D command (for “disassembly”) followed by the address. Try this now: D 1800
The instructions you entered appear at the top. Notice that the disassembly continues into the junk data region. The disassembler doesn’t know that those values are meaningless, so it just displays what those bytes would be as assembly instructions, even though it’s nonsense.
To execute a subroutine from the monitor, use the J command (for “jump”) followed by an address. When the CPU encounters the RTS instruction, it returns control back to the monitor, just as it does with SYS in BASIC. Note that if you write a subroutine that never reaches the RTS instruction, control will never return to the monitor. In most cases, you can hold Run/Stop and press Restore to return to the READY. prompt without losing your program in memory.
Here’s a variation of the border color subroutine without an RTS instruction. Use the monitor to assemble it at address $1800, then run it:
For more information on the ML monitor’s features, see the manual. I also wrote a tutorial on the MEGA65 Monitor as part of a series on introductory assembly language.
The machine language monitor is super useful for understanding how machine language programs work, and for troubleshooting programs and examining memory. Even so, you would not write large programs this way. A full-fledged assembler application gives you essential tools for managing large amounts of code.
Mega Assembler by grubi is an assembler for the MEGA65. It includes a source code editor with built-in help features, and can assemble and run your programs, and save them to disk. Check out the example programs included on the disk image to get a feel for how it works.
One of the most useful features of an assembler is its ability to assign labels to the many numbers that appear in a machine language program. Here’s a version of the border color program for Mega Assembler that is easier to read than the raw instructions you entered into the monitor. (Mega Assembler needs the lines indented as shown.)
The MEGA65 manuals are the best and most complete reference for the MEGA65, but they do not yet contain introductory material for machine language programming. Thankfully, many books about machine language programming for the 6502/6510 CPU and the Commodore 64 apply to the MEGA65. The memory locations are different, and the MEGA65’s 45GS02 has more advanced features, but C64 programming books are still a valuable resource.
Check Archive.org for scans of popular assembly language books, such as:
Despite my struggles with it as a small child without the benefit of the Internet, the chapter of the Commodore 64 Programmer’s Guide on machine language is a good introduction to the topic.
With a built-in machine language monitor, a freely available assembler, and access to hundreds of websites and PDFs, it’s so much easier to learn how to write machine language programs for the MEGA65 today than it was for the Commodore 64 in 1986. I hope you give it a try, if only to get a sense of how the computer works, on its own terms.
See you next month!
— Dan
Exploring MEGA65 hardware. Dan’s MEGA65 Digest for January 2023.
I think many of us were first attracted to the MEGA65 project for its hardware: the Cherry MX keyswitches in an authentic Commodore layout, the precision recreation of the Commodore 65 injection molded case, the 3-1/2" floppy drive—not to mention modern conveniences like HDMI video out and an SD card slot. It has taken nine years of hard work and persistence of vision to bring this project to the point of being something everyone can purchase and enjoy.
In this Digest, we’ll look at the recent history of the MEGA65 hardware, including the Nexys FPGA development board on which most of the firmware was written. We’ll take a tour of peripherals that work with the MEGA65, both vintage and new. And we’ll look at hardware experiments in progress that may provide a glimpse of the MEGA65’s future.
But first!
The latest batch of MEGA65s is being delivered, and it’s been super exciting to see all of the messages and photos from proud new owners in the Discord. If you’re a new owner, welcome to the world of personal computing!
We have many more resources for getting started with your MEGA65 than we did a year ago. There’s a new documentation landing page, which has links to the latest version of the User’s Guide.
Last year I wrote a MEGA65 Welcome Guide intended to help new owners get up and running. I’ve been keeping it up to date to be useful whether you received your MEGA65 last May or this January.
You’ve already found this Digest. You might also enjoy the back issues, available on the website.
That documentation landing page is part of the MEGA65 Wiki, a relatively new resource that we’re still building. If you’d like to contribute to the wiki, reach out to Gurce on the Discord chat server. You can also read and post articles on Filehost, another great resource.
It’s the Digest’s first recurring segment! Here at Featured Files, we look at cool stuff that has been posted to the MEGA65 Filehost. Download and try these on your MEGA65 today!
Mega Sisters, by Endurion
Mega Sisters, by Endurion. A version of the 1987 Commodore 64 classic The Great Giana Sisters, this multi-stage adventure pays homage to familiar side-scrolling platformers while adding a few twists of its own. Endurion, aka Georg Rottensteiner, is the author of C64 Studio, a Commodore cross-development IDE for Windows. You can download the source code for this MEGA65 game. Use a joystick in port 2; move up to jump.
Battle Sparrow, by gurce
Battle Sparrow, by gurce. A vertical scrolling space shooter in the vein of Warhawk for the C64 (1986), this action game was written entirely in MEGA65 BASIC with PETSCII graphics, vibrant colors, and a rockin’ soundtrack. Use a joystick in port 2.
Barnsley Fern Fractal, by heath8041
Barnsley Fern Fractal, by heath8041. This elegant BASIC program renders the Barnsley fern at a resolution of 640x400. The disk image includes several programs to render the fractal in different ways. Run it yourself, or watch Heath-man’s video.
When you pre-order a MEGA65 from Trenz Electronic, you can expect to receive a faithful recreation of the unreleased Commodore 65 personal computer, with a few modern improvements. The first step of this experience is opening the rainbow-colored “retail” cardboard packing box. Inside the box is the MEGA65 computer, with its authentic injection-molded plastic case, keyboard with authentic layout and keycap designs using modern mechanical keyboard switches, and a refurbished 3-1/2" floppy drive.
The ports on the back and side of the computer are a mix of modern and familiar: a barrel-jack power connector, a C64-style cartridge port, an IEC serial port, VGA and HDMI video output, an ethernet jack, a microSD card slot, stereo audio output, and two DE-9 ports for joysticks, paddles, and mice.
Inside the MEGA65 is a circuit board populated with chips and connectors. Compared to its vintage ancestors, the MEGA65’s board is surprisingly spare, with less than a handful of devices that you might call chips and lots of empty green space. Also surprising are what appear to be extra unused connectors for diagnostic devices, additional stereo audio outputs, and unspecified peripherals. The keyboard is a separate device connected to the main board with a ribbon cable, as is the floppy drive. The main board also sports a removable full-size SD card pre-populated at the factory with software, and a CR1220 battery holder for the Real-Time Clock.
At the center of the MEGA65 is the Xilinx Artix-7 FPGA chip, a modern device that can be programmed to behave like other digital logic devices. Importantly, the FPGA replicates these behaviors electronically, as if these digital designs were etched in silicon. The MEGA65 firmware (or core) describes a complete chipset that in 1991 would have been a dozen permanently-etched chips arrayed across the board.
The MEGA65 has two smaller FPGA devices on the board, an Altera MAX10 for various electronic functions, and a Lattice device for the keyboard. There are three FPGA devices in total in the MEGA65.
This is the MEGA65 in its official form. It’s what you buy from Trenz Electronic, and it’s what the MEGA65 team does its best to support with regular testing and improvement of the firmware and system software. The MEGA65 has taken other forms in the past, and the expandability of the machine and open licenses of the designs are meant to encourage experimentation. Naturally, you install such expansions at your own risk.
The MEGA65 as we know it went through multiple stages of hardware development over the years. Most of the MEGA65 core was built on the Digilent Nexys A7-100T FPGA trainer board, a bare circuit board that electronics designers use to evaluate the Artix-7’s capabilities and learn how to use it. The circuit board is “bare” in the sense that it doesn’t come with its own plastic case, but it is actually quite crowded with features, with connectors and hardware interfaces of various kinds, push-buttons, and a set of seven-segment LED numeric displays. Important to the MEGA65 project, the trainer board includes VGA video output, monaural audio output, a USB port for a PC keyboard, and a microSD card connector.
While the Nexys board is not an officially supported configuration, the MEGA65 team still provides downloads of the MEGA65 core for the Nexys A7. You can buy a Nexys board for $350 on Amazon, install the MEGA65 core, set up the microSD card, and put together a capable MEGA65 rig. This configuration lacks the eight megabyte RAM expansion of the MEGA65, but this is a documented variation, and many software titles can run without it.
Note that the Nexus A7 board is also known as the “Nexys4DDR,” which is the name you will see in some documentation. This is not the same as the older board known as the “Nexys 4,” which was also used for MEGA65 development at one point.
You can program the Artix-7 FPGA using the m65 command-line tool provided by the MEGA65 project, or with Vivado ML: Standard Edition, the free version of the official professional FPGA development suite from Xilinx. Connect your PC to the “PROG UART” microUSB port on the board.
Support for the USB host port is limited and doesn’t work with USB hubs. You can connect a standard USB PC keyboard to this port, though be warned that fancier keyboards tend to act like USB hubs, so be sure to look for something cheap. A PC keyboard does not have the MEGA65 key layout, but all of the MEGA65 keys are mapped to PC equivalents.
For serious tinkerers, you can enhance your Nexys board with the DM65PIC MEGA65 widget board, designed by Dieter Penner. The widget board connects to the Nexys’s PMOD ports and provides connectors for an authentic Commodore 64 keyboard, a Commodore 65 keyboard (if you’re lucky enough to have one), and two DE-9 ports for joysticks, paddles, or mice. You’ll have to get a board fabrication shop to make it from the Eagle design files, and depending on which shop you use you may need to solder some or all of the surface mount components. You’ll also have to program the microcontroller using the software in the repo. It’s a significant project, but can make for a satisfying build. See sy2002’s demo video to see the widget board in action.
While you’re at it, whip up a 3D-printed case for the Nexys using community-provided design files. I don’t have my own 3D printer, so I use 3D printing services like ShapeWays. It’s pretty amazing how we can send homemade design files for things like plastic shapes and circuit boards to fabrication services, and have them in our hands weeks later, for not much money.
Because the Nexys board was the only way to develop for the MEGA65 project for so long, there are excellent set-up instructions in the Developer Guide. Also check out the article and video by RetroCombs: Install the MEGA65 on a Nexys4 or A7 FPGA (2021).
Between the Nexys trainer board and the MEGA65, there were two revisions of the main board. It is occasionally useful to understand the board revision identifiers, especially when locating the firmware release for your computer.
There were early main board designs known as “R1” and “R2.” These were not distributed, so you won’t see these in the wild.
In the year 2020, the MEGA65 project produced and sold 100 “DevKit” units, with cases made from laser cut acrylic. The DevKit main board is revision “R3.” It has four slots for firmware cores, and includes eight megabytes of additional RAM (known as “attic RAM” or “HyperRAM”). DevKits came bundled with USB JTAG hardware for testing new cores and doing cross-development of software. You can only flash a new core to slot 0 of a DevKit using the Vivado software.
The latest main board in today’s MEGA65 is known as revision “R3A.” The differences from the R3 board are minor: there are eight core slots instead of four, and there are some minor electrical changes. The R3A board can only be flashed by the m65 tool and not the Vivado software suite, but you can flash a new core to slot 0 without Vivado.
From an architecture standpoint, the Nexys, R2, R3, and R3A boards only differ with regards to the Attic RAM: whether it’s present or absent, how much there is, and how fast it performs. The core and system software intend to continue supporting these differences, and software that uses Attic RAM can test for its presence to run cleanly on all boards.
You’ll see these board revision identifiers in the names of the different versions of the MEGA65 Core Release Package on Filehost:
The MEGA65 tries to be compatible with some vintage Commodore peripherals and their modern counterparts. Here’s a quick rundown of a few that I’ve tried. If you have your own experiences or recommendations, be sure to post them to the #peripherals channel in the Discord.
Vintage joysticks meant for Commodore and Atari computers work well with the MEGA65. They connect to the DE-9 ports on the left side of the computer.
If you’d like to use a Sega Genesis gamepad controller, be sure to use a C64 Genesis adapter. Sega Genesis controllers use DE-9 connectors, but use different wiring that can damage a Commodore. It’s not obvious how much damage it might do to a MEGA65, but it’s mis-wired regardless and I’m not willing to try it to find out.
I prefer a modern gamepad controller wired for the C64. They look and feel like Nintendo controllers, and they wire the second button to “up,” which is used to jump in platform games.
For a modern joystick, I like the ArcadeR. It puts an arcade-quality stick and buttons in a featureful, mod-able case, and has options like auto-fire and two-button support. Another option is the Hyperkin Trooper, a good choice if you’re looking for the vintage shape without roughing up vintage equipment.
The Hyperkin Ranger has a gamepad form factor, and also includes a single wheel for paddle games. Specifically for paddles, I recommend looking for vintage Atari paddles on eBay. They appear to be plentiful, inexpensive, and in good condition, at least for now.
The MEGA65 supports the Commodore 1351 mouse, the Amiga mouse, and anything that can act like either of these. The 1351 tends to be more reliable.
The MEGA65 must be configured to recognize either the 1351 or the Amiga mouse. Hold the Alt key while turning on your MEGA65 to start the Configuration tool, then set each port to the desired mouse type under the “Input” tab. Connecting an Amiga mouse while in 1351 mode may interfere with the behavior of the keyboard, so if you’re having difficulty, just unplug the mouse and check your settings.
The mouSTer is a clever modern device that lets you connect a USB mouse to a DE-9 Commodore port. It’s quite versatile, and you can set a variety of options by connecting a USB drive containing a config file. The mouSTer can be configured to emulate either a 1351 or an Amiga mouse, so make sure it matches your MEGA65’s settings. I use my mouSTer with an inexpensive Logitech M185 wireless mouse. If I’m not desperate for the Commodore tank mouse look and feel, I prefer my Logitech.
I’m looking forward to trying modern retro mice recreations like the Tank Mouse when I get one.
The MEGA65 has an IEC serial port, most often used on Commodores with external disk drives. You can use a vintage external 1581 drive with the MEGA65 in C65 mode. Other IEC devices don’t work so well with C65 mode at the moment due to known timing issues inherited from the Commodore 65 ROM. C64 mode (type GO64) does better in some cases. I was able to get my Blue Chip D12 daisy wheel serial printer to work in C64 mode. Improving IEC device support in C65 mode is on the to-do list for the ROM.
The FTDI JTAG adapter is a peripheral that mounts to the primary JTAG port on the main board. With your PC connected to it with a mini-USB cable, you can install bitstreams, send programs, transfer files, and debug issues. If you don’t need to install bitstreams, you can use a cheaper and easier-to-find USB serial device connected to the UART pins of the JTAG connector. USB serial communication is great for cross-development and debugging.
Work is in progress to make it possible to transfer files and programs, and perform other cross-development tasks like debugging, using the MEGA65’s ethernet port, with no need for a separate adapter. If you’re interested in helping test this feature, inquire on the Discord. There’s a test core and new versions of the command-line tools that demonstrate this capability.
To round out this discussion of peripherals, we might as well mention the Real-Time Clock replacement. This is a peripheral that uses the Grove connector on the main board. The replacement RTC was our workaround solution for the small percentage MEGA65s that shipped with faulty real-time clock chips. The latest firmware detects when the replacement RTC is connected and communicates with it over the Grove connector.
One of the biggest hardware challenges for the MEGA65 project is the limited availability of FPGA chips. Trenz Electronic can only acquire so many of the FPGAs at time, which limits their ability to build and deliver computers. Even the price of a Nexys trainer board has gone up $80 in the last year. We all hope this shortage is temporary, but it may be a few years before we see supply return to previous levels.
MEGA65 founder and hardware designer Paul Gardner-Stephen is experimenting with a prototype for a lower cost keyboard that doesn’t need its own FPGA. The “DIY keyboard” project intends to be a drop-in replacement for the current MEGA65 keyboard, using the same Cherry MX switches and keycaps, and fitting perfectly in its case with no noticeable difference to the user. It can also be a standalone C65 keyboard for the Nexys board, connected to a PMOD port. You can use the open hardware design files to send away for a bare board, and install your own switches and keycaps. As pictured above, MEGA65 owner mpryon completed his Nexys rig with a DIY keyboard based on Paul’s prototype design.
It’s too early to say whether the DIY keyboard will become a more polished product for sale. It’s easy to imagine it being sold as a kit with a set of official MEGA65 keycaps, or adapted via microcontroller to be a USB keyboard with a C65 layout for use with the Xemu emulator. You can follow Paul’s progress on the DIY keyboard on his developer blog: October 2022, November 2022, December 2022
Paul is also working on a prototype for a port expansion board that adds component video output, a Commodore user port, a tape port, and a port for the unreleased C1565 external floppy disk drive. The board would mount inside the MEGA65, and place the new ports through the punch-outs already prepared in the back of the plastic case.
Why add a port for an unreleased Commodore peripheral? So you can recreate the peripheral, of course! It’s just an idea for now, but the 8-pin mini-DIN connector for the C1565 external floppy drive could support an actual vintage prototype drive, or an all-new project to recreate the drive with a case that matches the MEGA65. At the very least, the port would make the MEGA65 more authentic, matching the similar port on the Commodore 65.
As with the DIY keyboard, there are not yet plans to produce the expansion board in quantity. You may be able to make your own from open designs at some point. Paul is also dev-blogging progress on the expansion board: October 2022, January 1, 2023, January 6, 2023.
For several years, the MEGA65 website advertised not only an upcoming reproduction of the Commodore 65, but also a mobile phone based on the same technology. Today, the website focuses on the first project, which, obviously, is now in full swing and in the hands of hundreds of happy owners. Is the mobile phone project still a thing?
Let this be a lesson: never bet against a project with strong principles. The MEGAphone is still in active development, and making good progress. With a grant from the NLNet Foundation, the MEGAphone seeks to reclaim one of the most important technological spaces in the daily lives of billions of people.
The idea is this: The sheer complexity of modern computers alienates us from the technology upon which our digital lives depend. It’s not enough for a smartphone operating system to be open source in theory, as Android claims to be. To achieve the benefits of this transparency—security, privacy, control in the hands of the user—the technology has to be strictly modular, and simple enough for a computer hobbyist to understand. The Commodore 65 is one of the last practical computers to fit this description. What if there were a smartphone based on the Commodore 65?
The MEGAphone is a proof-of-concept portable device with mobile telephony, Internet, and a touch screen interface. It uses the MEGA65 core and ROM, and can run MEGA65 software, including software written by the phone’s owner. Everything is open source, and any owner can replace any component on their phone as easily as they can on the MEGA65.
To learn more about the project’s goals, watch video of Paul’s 2019 talk, Creating Resilient and Sustainable Mobile Phones. For a glimpse of recent progress, see his recent dev-blog entries about the MEGAphone: September 7, 2022, September 14, 2022, September 20, 2022.
The MEGA65 hardware released in 2022 is a huge milestone for the project and for vintage computer preservation in general, the culmination of nine years of work to realize the vision of Commodore’s designers and engineers with modern components and techniques. The result is a multi-layered hobbyist platform that will continue to see revisions, adaptations, and expansions into the future.
If you’d like more information on any of these projects, or if you discover something interesting or build something cool, be sure to let the community know in the Discord.
Until next time!
— Dan
Back to BASICs. Dan’s MEGA65 Digest for December 2022.
One of the most satisfying things you can do with a vintage computer is to turn it on and start writing a program. With nothing but your curiosity, a little persistence, and maybe a book and a pad of scratch paper, you can craft a program that solves a problem, performs a task, produces a work of art, tells a story, or generates an interactive experience.
In this Digest, we’ll look at a few ways to get starting writing programs for the MEGA65 using the built-in BASIC 65 programming language. This won’t be a BASIC tutorial—there are hundreds of vintage books on that subject, and you already have the MEGA65 User’s Guide. There are additional chapters for beginners in the MEGA65 Complete Compendium. Instead, we’ll focus on several ways to create and run BASIC programs with your MEGA65, and with your PC.
But first!
Trenz Electronic has announced that batch 2 shipping has begun, and some have already received their MEGAs! The next 400 recipients should receive shipping notices in the next few weeks, followed soon after by receipt of your very own MEGA65.
Batch #3 is expected to deliver in the third quarter (July-September) of 2023. It’s too early to say how many units will ship in the next batch. Here’s hoping that FPGA supply will be flowing more freely next year.
For those of us awaiting delivery of a pre-ordered MEGA65: If your shipping address has changed since you placed the pre-order, send an email to: [email protected]
Changing the shipping address in your Trenz Electronic website account settings will not update shipping addresses on pending orders. You must send them email to update the address on a pre-order.
I know many of us have been waiting a long time for our MEGA65s. If your address needs updating, take care of it soon to ensure smooth delivery.
You’re probably reading this Digest delivered as email via Substack. If you clicked through to the audio version with the play icon at the top of the email, you’re probably listening to it using a web browser on your desktop computer, tablet, or smartphone. You can read past and current issues, as well as manage your email subscription, on my website: dansanderson.com/mega65/ Substack has a phone app, and it includes a built-in audio player.
Alternatively, you can follow the Digest using your favorite feed reader. You can usually just copy the website address into your feed reader to subscribe. If your reader needs the exact feed URL, it’s just this: dansanderson.com/mega65/index.xml
I’m pleased to announce that the audio version of the Digest is now available in your podcast player! Search for “Dan’s MEGA65 Digest” in Apple Podcasts or the Pocket Casts directory. Some (but not all) podcast players can subscribe directly to the website feed as if it’s a podcast.
Regardless of how you follow the Digest, thanks for being here!
Like the Commodores that precede it, the MEGA65 starts up with a blinking cursor at the READY. prompt. You can enter a command by typing the name of the command followed by arguments, and execute the command immediately by pressing the Return key. For example, here’s a command to turn the color of the screen border to black:
You can use the same blinking cursor to write a program, a collection of commands on numbered lines. If you type the BORDER command after a line number then press Return, it does not change the border color, but instead stores the command to be run as part of the program.
Here’s a short program that prompts for a temperature in degrees Fahrenheit, then displays the equivalent temperature in degrees Celsius. Try typing these lines into your MEGA65:
If you’ve written a program on a Commodore before, this should feel familiar. The BASIC screen editor allows you to type whatever you want anywhere on the screen. When you press Return, it checks whether the line with the cursor on it begins with a line number, and if so, it stores the contents of that line in BASIC program memory. If there’s already a line in memory with that line number, BASIC replaces the old line with the new one.
It’s important to remember that what’s on the screen does not necessarily represent the program stored in memory. You can think of the screen as a sort of scratch pad on which you can type whatever you like. Only when you press Return on a line will BASIC try to do something with what you typed.
To see the lines of the actual program stored in memory, use the LIST command.
If you notice a mistake or something you’d like to change, you can move the cursor up to the line displayed on the screen, type new text over the old text, then press Return to replace the line in memory.
BASIC keeps the program in line number order, but you can enter the lines in any order you like. This is handy for inserting a line between two other lines: pick a number between the numbers of the existing lines, and enter the new line with that number. This is why BASIC programmers tend to number their lines by tens (10, 20, 30…), to make it easy to insert a line in the middle of the program (15).
To delete a line, enter the line number with no text after it. To delete a range of numbered lines, use the DELETE command followed by the range:
To erase the entire program from memory, use the NEW command. If you do this accidentally and want to bring the deleted program back, don’t panic, just type: NEW RESTORE
Your program is in the computer’s memory, but it is not saved to permanent storage automatically. (Maybe that’s obvious in the context of vintage computers, but we get accustomed to modern conveniences sometimes.) If you turned off the MEGA65 now, the program would be forgotten.
Hopefully by now you’ve had a chance to mount a D81 disk image and load a program from it. You can also use the Freeze menu to create an empty disk image on your SD card. Try this now: hold Restore for a second then release to open the Freeze menu. Press 0 to mount a disk to device 0 (unit 8). At the top of the list of disk images is the option to create a “NEW D81 DD IMAGE.” Select this, then give the disk a name. I like to call my work disks “WORK” to make it seem like I’m doing something important.
The new disk image is now mounted. Press F3 to resume to BASIC. (Be careful not to press F5 to reset if you have a program in memory!)
With a BASIC program in memory, save it to your disk with the DSAVE command. Put the filename in double-quotes:
Confirm that your program is on the disk by listing the disk directory:
As written, the DSAVE command will fail if there is already a file with that name on the disk. It’s a common practice to save your work periodically with different filenames suffixed with increasing numbers, so you can revert back to an older version if necessary. (Commodores don’t have built-in revision control systems!) Over a few days, you might end up with "TEMPCONV2", "TEMPCONV3", "TEMPCONV17" on your disk, until you’ve decided which version is the final version.
Alternatively, you can live dangerously and overwrite the same file each time you save. To do this, prepend the filename with an “at” symbol (@). (The symbol is not considered part of the filename.)
You can now turn off your MEGA65. The next time you turn it on, you can use the MOUNT command with your work disk name followed by .D81 to mount it, then the DLOAD command to load your program back into memory:
Eventually your program will be many lines long. The LIST command will try to list your entire program, and only the bottommost 25 rows will be on the screen at the end. How can we navigate a long program listing?
(If you want to experiment with this without writing a long program, MOUNT "MEGA65.D81" then DLOAD "AUTOBOOT.C65" to load the demo disk’s menu program, which is written in BASIC. If you disabled opening the menu on start-up, this file has been renamed: use DLOAD "MENU" instead.)
As with previous Commodore BASICs, the LIST command accepts a range of line numbers. This is a slightly cumbersome but precise way to look at a few lines at a time, if you know their numbers.
When listing many lines, you can tap the No Scroll key to pause the listing. You can press Run Stop to terminate a paused listing, or No Scroll again to resume. The MEGA65 is so fast in its default 40 MHz mode that this isn’t a practical way to peruse a listing. You could use the SPEED 1 command to set it to 1 MHz and slow it down, but be warned: there’s a bug where the MEGA65 crashes when you Run Stop in slow mode! I don’t recommend this method at all for this reason—but I mention it because it’s interesting.
The MEGA65 LIST command has an option to display a program listing one screenful at a time:
Press a key at each page to advance to the next one, or press Run Stop to abort at the current page.
There’s a third method to browse long listings, and it’s my favorite: press F9 and F11 to scroll down and up by a line. (If you’ve redefined your function keys, you can use Ctrl-P and Ctrl-V instead.) I like this method because the screen editor remains active, so you can start typing inside the listing as soon as you see what you want to change. Notice that the screen does not have a modern-style scrollback buffer, even though it seems like it does: it’s actually reading lines from BASIC memory to fill in the scrolling display.
With lots of text on the screen, remember that you can get new blank lines to type on by running the cursor off the bottom of the screen, or pressing Shift + Clr Home to clear the screen entirely. You can also clear just from the cursor’s line to the bottom of the screen by pressing the ESC key followed by the @ key.
The BASIC 65 screen editor is thoroughly retro and thoroughly Commodore, and it picked up some nice features along the way from the Commodore 128, Commodore 65, and a few added by the MEGA65 team. But perhaps you want a coding environment that’s a bit more modern—without leaving your MEGA65.
The Eleven programming environment, by Stephen Kleinert (username ubik), reinvents the BASIC 65 editing experience. It provides a modern-style code editor and extensions to the BASIC 65 language to make it easier to use for large projects. It dispenses with line numbers, and instead uses labels for flow control (such as goto statements). Variable names can be longer than two characters, and preprocessor directives allow for efficient definition of constants without taking up variable space.
The brilliant part is that Eleven compiles your program into plain BASIC 65 code. It generates line numbers, replaces labels, renames variables, strips comments, and minifies syntax. The result is a compact BASIC 65 program that you can save to disk and give to your friends, with no bulky runtime library or other baggage. BASIC 65 is a powerful enough language; Eleven just adds modern documentation and editing conveniences, making BASIC programs easier to write and maintain.
A copy of Eleven was included on your SD card, and you can download the latest version from Filehost. Here’s how to give it a try:
Eleven will insist that you save your changes before compiling, so you won’t lose anything if your program crashes the machine.
Stephen has released Eleven to the MEGA65 project with an open source license. There may be on-going improvements in the future.
Coding directly on the MEGA65 with the printed User’s Guide at your side is a cozy, comfortable experience, free of Internet-y distractions. But sometimes—just sometimes—I want to use modern tools to develop retro software, even if I’m writing in BASIC.
Full disclosure: I’m a developer tools nerd. I like storing text source files in a Git repository, running things through multiple levels of processing, and automating it all together with Makefiles. One of my favorite ways to write MEGA65 BASIC is on my PC.
I use a command-line tool called petcat that converts a text file containing BASIC code into a PRG file that I can run on my MEGA65 or in the Xemu MEGA65 emulator. petcat comes with the VICE Commodore emulator suite, which I have installed for all of my non-MEGA65 Commodore projects. VICE doesn’t provide a MEGA65 emulator (that’s what Xemu is for), but petcat does know about BASIC 65 commands.
That temperature conversion program looks like this in a petcat text file, literally the same text but in lowercase:
To convert this to a MEGA65 PRG file, use this shell command:
You can test the PRG file in Xemu by dragging it into a running Xemu window, or by starting Xemu with appropriate command-line options. If you happen to have a JTAG USB adapter, you can beam this PRG file directly to your MEGA65 with the m65 command-line tool or with the M65Connect app (search for “M65Connect” on Filehost).
You might notice that a text file on a PC doesn’t seem to be capable of representing everything that might go in a BASIC program. For example, there are characters on the MEGA65 keyboard that are not present on a PC keyboard, like the Up Arrow symbol. How would a petcat program print the graphical glyphs on the front of the keys, like the heart shape on the S? What about the PETSCII control codes, like Ctrl-3 that changes the print color to red?
petcat represents as many characters as it can with ASCII equivalents. All of the right-hand glyphs that you access by holding Shift and pressing a letter are simply the capital letters. The PETSCII symbols for pound, Up Arrow, Back Arrow, and pi are represented by ASCII characters with the same encoded value: \, ^, _, and ~, respectively.
Nearly everything else appears in a petcat listing as a label inside curly brackets, such as {red} for Ctrl-3. For example:
The left-hand glyphs that you access by holding Ctrl and pressing a letter are labels like {CTRL-A}. A few codes that are typed with the Mega key look like {CBM-@}. Other PETSCII control sequences have named labels like {clr} or {stop}.
I won’t clutter this Digest with a complete list. I’ll just say that petcat also knows how to convert a PRG file back into text. If you’re unsure of what label to use for a character or control code, you can create a small program with the character in it using the MEGA65 or Xemu, then run petcat in reverse to see what it looks like.
If your PC runs Windows, there’s a compelling new option for MEGA65 cross development. CBM PRG Studio is a much loved integrated development environment for writing programs for Commodore computers. Starting with version 4.0, it includes support for the MEGA65.
I don’t normally use windows, so I’m not deeply familiar with CBM PRG Studio’s features. But it took me no time at all to figure out how to use it to write a MEGA65 BASIC program and build the PRG file. It looks like a compelling IDE for Kick Assembler, as well. Give it a try!
Maybe you’ve written a program on your MEGA65 and saved it to a D81 disk image, and now you want to extract the PRG file on your PC. Or perhaps you’ve written a PRG on your PC, and want to put it in a D81 disk image for the MEGA65. We’ve got tools for that!
Windows users should go straight to DirMaster, a powerful disk image management tool that supports many formats, including D81. You can create new images, open existing ones, copy files to and from images, and much more.
Mac and Linux users will prefer droiD64, a desktop app similar to DirMaster. It has fewer features, but I like it because it’s fast and works on all operating systems. It requires a Java 11 runtime, such as OpenJDK or the Oracle Java runtime. I wrote a bit more detail about droiD64 in a recent blog post. Check that out for a technical recommendation on how to improve the start-up script that comes with droiD64.
Of course, I did say I was a developer tools nerd, so naturally my build scripts use command-line tools to create D81 image files. VICE comes with a tool called c1541, and cbmconvert (download) is another option. Personally, I write my own D81 build logic in Python with the d64 Python library. Most people will get by just fine with DirMaster or droiD64.
It’s the end of the year, and I hope everyone is able to take some time off, disconnect from the Internet a bit, and spend some quality time with your MEGA65, and maybe family and friends too if you get around to it. When you get back online at the end of your break, don’t forget to share your BASIC programs by uploading them to Filehost!
I hope you’re all doing well this holiday, and I hope to see you again in 2023.
— Dan
From the publisher's feed