Tag

Showing blog posts sorted under the tag: dreamcast

Building a GD-ROM Optical Drive Emulator for Sega Dreamcast

EmeraldGD prototype installed in a Dreamcast.

The PIO (programmable input/output) hardawre on the RP2040 and RP2350 chips has been a game changer in a lot of applications. After getting familiar with using PIO to interface with the Dreamcast's controller port, I started experimented talking directly to the console through its GD-ROM interface.

The idea came from hearing about another project, PicoIDE, an IDE emulator for retro computers using the RP2350. I had also read that the Dreamcast interfaced with the GD-ROM via ATA, and so thought the RP2350 could probably be used here too.

So, for the past 6 months or so, I've been working on a Dreamcast ODE called EmeraldGD that also uses the RP2350 chip. It reads GDI and CDI disc images, handles the Dreamcast's normal ATA timings in both PIO and multiword-DMA modes, and supports CD-DA for games that use digital audio.

It's not quite a performant as other ODE solutions. This is due to using SPI to read data from the SD card, which can be pretty slow, and not being very efficient fetching data from the SD card. The ATA interface itself runs at full speed. So, there's still room for improvement.

I also tried to make it compatible with the latest version of OpenMenu, at least the simplest case of choosing a game and launching it works. OpenMenu and GD MENU Card Manager are both super convenient for managing games.


Even though the Dreamcast's GD-ROM connector is somewhat proprietary, it basically just brings the ATA and CD-DA (CD digital audio) interfaces together on one plug.

So, I harvested a GD-ROM connector from an old GDEMU board and built a little breakout board to collect traces from a GDEMU and to connect my RP2350 dev board to the Dreamcast. A cheap 16 channel 200MHz analyzer was just fast enough to capture ATA activity. 16 channels is not enough for the whole bus but it worked out all right since I usually only cared about a subset of the bus at any one time.

RP2350 dev board connected to a Dreamcast.

ATA

The Dreamcast uses standard parallel ATA to talk to the GD-ROM drive, which is quite an old standard by now. There's a lot of high-level descriptions of ATA online but finding really detailed stuff was weirdly difficult.

I did manage to find a nice document here that describes the ATA and ATAPI spec and was quite helpful to get a decent understanding. Claude (AI I know) was also really helpful in generating timing diagrams for different ATA operations. Comparing live traces to the documentation also helped a ton.

At a really high level, ATA is basically just a protocol for a host to read from and write to registers of a device. Several lines of the bus are used to setup a read or write, then the data lines get filled with required data. The data lines get sampled, and the whole process starts again.

For a read, when the Dreamcast pulls DIOR low, the drive needs to put the value of the requested register on the data lines as soon as it can. For a write, the Dreamcast pulls DIOW low then the drive just samples the data lines and writes that value into the chosen register.

A sample ATA trace showing a register write, followed by a read.

The above trace (captured from a Dreamcast talking to EmeraldGD) shows two register operations: a read followed by a write, as indicated by first DIOR then DIOW going low.

The write in this trace is actually quite special, it is writing the value of 0xA0 to the Command register. This is part of the ATAPI interface and kicks off a Packet Command. When the drive receives this command code, it gets ready to receive a payload of data for a more complicated command like reading sector data from the disc, or getting the disc's table of contents.

On the Dreamcast, register reads and writes are typically 100ns. To put that into perspective, I set the clock speed of the RP2350 to around 200MHz, which means each clock is about 5ns, so there are only 20 clocks to get data on the lines. Way too fast to bitbang, but the RP's PIO hardware makes this possible.

Using PIO to Talk ATA

To be able to interface with the Dreamcast via ATA, the RP2350 needs to basically just do two things: sample data when a register write is given, and get the correct data on the data lines when a read is detected. Since it is the host that drives the read/write signal lines, these are the timing-critical pieces that the PIO blocks need to take care of.

Dealing with writes was pretty simple, I created a small program that just waits on the DIOW line to go low, then high, then sample the bus into a buffer. The CPU deals with writes on its own time. Pretty much every write I encountered from the Dreamcast was in preparation for a packet command, so as long as the write buffer is flushed before dealing with any commands, everything seemed to work well.

Read requests were the much trickier task. There's absolutely no way that a PIO program would be able to get data from the CPU within the 100ns window, remember that's only 20 clock cycles! The solution I found was to use a new feature of the RP2350 chip that allows it to access arbitrary entries in its RX FIFO.

Each PIO state machine has 4 32-bit entries in its RX FIFO (enough for 8 16-bit registers) which are usually used for sampling data, but it's also possible to use them in a sort of 'register' mode where the 4 entries can be accessed arbitrarily via the mov instruction.

So, I get the address of the requested register from the address lines, then grab it from the RX FIFO using: mov osr rxfifo[y]. I still update the registers on the CPU side, but the PIO program can always respond to reads without needed to go to the CPU.

In addition to register access there are also two ways to transfer larger chunks of data from the drive to the Dreamcast. The more basic method is called PIO (unfortunately named the same as PIO on the RP chips). PIO transfers data via standard ATA register reads through the Data register. Basically, the console just reads the Data register a bunch of times until it has all the data it's expecting.

The way I handle this is with a separate PIO program (the RP's PIO this time) that is triggered with an interrupt when the Data register is read. This program is fed with the data from the CPU via the RP's DMA feature so it can push out 16-bits of new data every time the Data register is read.

A sample ATA trace showing a PIO data transfer from RP2350.

The above trace shows the start of a PIO data transfer, with the response data being supplied from the RP2350. A full Data register read cycle takes about 600ns, a theoretical limit of 3.3MB/s, pretty slow.

Another method of transferring data is called DMA (again an unfortunate name clash). Instead of reading data through the Data register, the Dreamcast and the drive do a bit of a handshake using some special-purpose DMA lines, then the Dreamcast just strobes the DIOR line continuously until it gets all the data it wants. This is much faster than PIO data transfers because it skips the whole setup for requesting a specific register.

This is was actually pretty easy to create a PIO program for. I feed a state machine with data using the RP's DMA feature and the state machine will just continuously pump out 16-bits of data from the buffer every time the Dreamcast strobes DIOR while in the DMA state.

A sample ATA trace showing a DMA data transfer from RP2350.

The above trace shows a DMA data transfer, with the response data being supplied from the RP2350. There's no register reads here, just the Dreamcast bringing DMACK (DMA acknowledge) low then strobing the read line. A single read cycle is about 140ns, a theoretical limit of about 14MB/s, or about 4 times faster than a PIO data transfer.

Most Dreamcast games that I tested tend to use DMA more than PIO, especially for really large data transfers. But, homebrew games using KallistiOS, I noticed tend to use PIO more frequently.

The ATA interface is also only one piece of the whole project, but it was the most interesting for me to work through, so I thought it was worth talking about here. There's lots more like: parsing disc image formats, dealing with different ATAPI packet commands, and of course CD-DA which is important for a lot of games. Maybe I will expand on some of that stuff in another blog post.

Compared to working with the Maple bus, the G1/ATA bus was much more forgiving. As long as the timings for register accesses are kept to, the Dreamcast will just kind of dutifully wait for a response to whatever it asked for, or whatever you tell it to expect. So, while it's certainly more complicated than the Maple bus, at least on the wire, but at the same time was a lot more straightforward to deal with in other ways.

Building a Prototype

Along with the firmware, I also designed a prototype board for use on a real Dreamcast. It's mostly using the RP2350 reference design as a base and just wiring up the GPIO to the GD-ROM connector. I'd never designed a board using a bare RP chip before so it was a fun experience. Those GD-ROM connectors also seem to be very hard to find and I ended up harvesting one from another GDEMU clone.

I went with the RP2354B chip because it has 2MB of built-in flash storage so is a bit cheaper than using an external flash chip, and keeps the board a bit smaller. The unused GPIO are also broken out just in case.

KiCAD render and prototype board.

Surprisingly (or not maybe? I just always expect the worst from my PCB designs) the PCBs came back working without any issues that I could see. I'm sure a proper engineer would be able to find quite a few issues with my board.

Anyways, now that I have an interface to the Dreamcast through the G1 bus, I was thinking about what else could be done with it. One idea was about OpenMenu's settings and Serial VMU features. There's no technical reason that those things couldn't be saved on EmeraldGD using a custom command packet. I think it would be super cool to leverage the serial VMU onto the G1 bus instead of a serial adapter, to essentially get unlimited VMU saves without any additional hardware.

Thanks for reading!


Tags:


Pico1Maple - Porting Pico2Maple from the RP2350 to RP2040

An often requested feature for Pico2Maple (a USB/Bluetooth to Sega Dreamcast adapter) is the option to run it on the RP2040 chip (original Pi Pico) in addition to the RP2350 chip (Pico 2). The RP2040 is much more common for projects similar to Pico2Maple, and boards based on the RP2040 tend to be a little bit cheaper than equivalent RP2350 versions.

So, recently, I wanted to make an earnest attempt to port Pico2Maple's firmware to run on the RP2040 chip. Overall, it turned out to be a pretty straightforward process. There were a couple hurdles, which I talk about here, but everything else just sort of worked for the most part.

Here, I wanted to discuss some of the changes that were required to port Pico2Maple's firmware to run on the RP2040.

PIO Pin Masking

The RP series of chips have a cool hardware feature called programmable input/output (PIO). These are like little tiny co-processors that can run at a fixed clock rate. Each PIO block has 4 state machines, each with a few registers, and access to a shared space of up-to 32 instructions from a very limited set of instructions.

The maple_rx PIO program in Pico2Maple uses a new pin masking feature that is only available on the RP2350. When a PIO program reads pins into a register using the mov instruction, it will normally read the all 32 pins starting at the user-defined base pin. This makes it hard to compare pin reads directly because the unused pins will fill the register with garbage data. The masking feature causes only the desired pins to actually be read into the register, the rest of the bits will be set to '0'.

Pico2Maple reads the Maple bus by continuously reading both Maple data pins and waiting for either of them to change, and taking some action depending on which pin changed and in which direction.

Recreating the masking behaviour on the RP2040 turned out to be relatively simple, albeit at the cost of a couple extra PIO instructions.

; Using masking
mov x pins    ; Read pins with masking, only the first 2 bits will have data

Becomes:

; Without masking
mov x pins    ; Read pins w/o masking, 2 bits of real data with 30 bits of garbage
mov osr x     ; Copy register into output shift register
out x 2       ; Shift out 2 bits into register x, recreating the masking behaviour

So, one problem solved.

Lack of PIO Blocks

Pico2Maple uses all 3 PIO blocks available in the RP2350. Both of the maple_rx and maple_tx PIO programs are close to the 32 instruction limit, so they were each given a dedicated PIO block. Since each PIO block has 4 state machines available, it would be theoretically possible to support 4 controllers at once from a single Pico 2. However, this never got implemented and the whole Maple stack continued to use 2 full PIO blocks. The third PIO block on the RP2350 is used by the wireless chip driver to run a SPI interface to the CYW43 chip.

However, this whole PIO setup poses a problem for the RP2040 since it has only 2 PIO blocks available. My first attempt to get around this was to try and reduce the instruction count of one of the Maple PIO programs, so that it could share the PIO block with the PIO-SPI program used to communicate with the wireless chip. Multiple programs can share the same PIO block, as long as their combined instruction count is under the 32 instruction limit, and use separate state machines. This sort of worked, both were able to run from the same block, but Bluetooth activity was causing a lot of crashes. My thought was that because the same PIO block was being managed on two separate MCU cores (Bluetooth on core 0, Maple on core 1) that there were some concurrency issues.

Rather than trying to work around that, I took another approach of using only 1 PIO block for all the Maple stuff and dynamically swapping out the maple_rx and maple_tx programs when needed. This left the second PIO block free for exclusive use by the wireless chip driver.

Getting the program swapping to work without disturbing the signal on the Maple data pins took a bit of finessing, made slightly more complicated by the fact that pin control swaps between the PIO, SIO (general GPIO control), and letting the Dreamcast take control. The state of the Maple pins had to be setup in a very specific way otherwise they would briefly change when pin control was changed between different hardware. Even a brief blip would cause issues on the Dreamcast side. But after a bit of trial-and-error, it all seemed to work well in the end.

The basic flow goes like this:

Initialize PIO and load maple_tx
    |
Read Maple: unload maple_tx, load maple_rx, start program
    |
Parse packet, prepare response packet
    |
Write Maple: unload maple_rx, load maple_tx, write packet
    |
Immediately loop back to reading as quickly as possible

The whole process does run a bit slower than before, since it takes some time to unload and load PIO programs, but it seems to work quite well. Even on WinCE games like Sega Rally 2, that are particularly annoying to deal with, everything runs as expected.

Marking critical Maple functions as 'no_flash' sped things up markedly as well. Marking functions as 'no_flash' causes the code to be copied to and executed from RAM. Normally code is loaded and executed from flash using the RP2040/2350's execute-in-place (XIP) feature, this can cause delays as code needs to fetched.

All the Small Things

That ended up being pretty much it in terms of major hurdles. The rest of the needed changes were just some housekeeping things like reducing the size of some pre-allocated buffers to make sure everything would fit in RAM. The RP2040 only has around 256KB of RAM (vs the over 512KB on the RP2350), and 128KB of that is taken up for the VMU. But there was still enough for everything else.

One kind of curious bug that cropped up was due to unaligned 32-bit accesses. Some elements in a packed struct were being accessed by first casting it to a uint32_t pointer, but the elements were not 32-bit aligned and this caused the RP2040 to crash. The RP2350 apparently supports such memory accesses but the RP2040 does not. Interesting to see little hardware differences like this.

And that's pretty much it. I hope to have some public builds available soon for folks to try out if they are interested.


Tags:


Dreamwave - Turning a Dreamcast Controller into a Bluetooth Wireless Gamepad

As the Pico2Maple project (a Dreamcast USB/Bluetooth to controller adapter) reaches a recognizable level of maturity. I started thinking about what else could be done with the same core Maple bus implementation and eventually decided on modifying a standard Dreamcast controller to work over Bluetooth. Using an Xbox controller on the Dreamcast is great, but sometimes you just want to use the real deal.

I use the Pico 2 W to emulate the Dreamcast's Maple bus, pretending to be the console itself, and send Maple packets to the controller. The controller happily reports back its current state when asked, and that can then be sent over Bluetooth. Taking it a step further, the Pico 2 W can also communicate with any peripherals connected to the controller. I use this to send image data to any connected VMU (Visual Memory Unit) that is received on a separate Bluetooth channel.

The end result is a wireless Dreamcast controller I can use on both a PC and on the Dreamcast itself (with some additional hardware), and have a working VMU display!

Dreamwave controller and Dreamcast.

Polling the Controller

The Dreamcast's Maple bus is the protocol that the console uses to talk to peripherals through the controller ports. For the most part, the console sends commands to a peripheral and the peripheral then responds appropriately. Request and response commands all have the same core packet structure, just with different data payloads relevant to a given command. And so, while Pico2Maple takes on the role of a peripheral responding to the console, it is not much of a change to turn this around and take on the role of the console requesting data from the controller.

This is exactly what is going on with this project. The Raspberry Pi 2 W sends commands to the controller as if it were a Dreamcast console. The controller then responds as it normally does and all is well.

Only 2 commands are needed to get the controller to start responding: GET_INFORMATION and GET_CONDITION. The GET_INFORMATION command requests some data about the connected peripheral. This includes stuff like its name, available functions, and power usage among other things. Well-behaved peripherals won't respond to any other commands until after responding to this information request, so it is always the first step.

Once the peripheral's information has been requested, we can start sending GET_CONDITION commands to the controller. This requests the current state of the controller, like what buttons are pressed and what the values of the analog axes are. This is recorded and used by the Bluetooth stack to send the controller state over Bluetooth.

Bluetooth

Dreamwave uses BTstack and its HID protocol implementation to send input state over Bluetooth. BTStack has some great examples, so it wasn't too much effort to initially get the device appearing as a Bluetooth controller on my PC.

Getting my desired reconnect and pairing behaviour did take some trial-and-error but I enjoyed learning more about Bluetooth. At power-on, Dreamwave will try to reconnect to it's last known host. This barely takes more than a couple seconds and feels great especially with Pico2Maple.

It will fall back into discoverable/pairing mode if it can't reconnect to the previous host which does take a bit of time, so the pairing experience is not perfect. But it means I didn't have to worry about wiring up another button to enter Bluetooth pairing. Another option would have been a controller button combo to trigger pairing. That might be a future improvement.

I did not write a driver for the controller but the Linux HID generic driver seems to pick everything up just fine. Steam let me remap the buttons to match an Xbox layout and I was playing Sonic Adventure DX in no-time. So, as long as Steam is running, everything just sort of works.

On a Dreamcast Console

I also wanted to use the controller on a real Dreamcast. To do this I added support for Dreamwave to Pico2Maple so it could connect to and treat this setup like any other controller, and that seemed to work great as well.

One of the really cool features I added to Dreamwave is the ability for a Bluetooth host to open up a second channel, separate from the HID stream, to exchange data back and forth. Currently, this is being used for sending VMU LCD display data from Pico2Maple to Dreamwave. This means that I still get to enjoy the experience of having a VMU in my controller and wireless input.

Only the VMU screen data is shared between Dreamwave and Pico2Maple, game saves and whatnot still happen on the console side of things. I would like to eventually share save data from a VMU plugged into the controller. I think that'd be pretty cool.

Hardware

Hardware-wise there isn't much to what I was able to put together. The brains behind everything is, of course, a Pico 2 W. That combined with a rechargeable battery and a bit of extra power circuitry is all there really is to it.

For the battery charging and discharging circuitry, the Pimoroni LiPo shim was a pretty convenient solution for this project. It takes care of charging the battery and has a built-in power button which saved me the effort of including one.

Raspberry Pi Pico 2 W and battery in a VMU-sized box.

I really didn't want to modify the controller at all for this project. These things are 25 years old by now and it feels wrong to chop them up. To minimize needing to make modifications to the controller itself, I built everything into a memory-card-shaped box that fits into the second expansion slot of the controller. I did cut away a small piece of the controller to make sure the wires could get where they needed to, but this was ultimately unnecessary and I do regret doing that.

Overall, the final product doesn't look too bad. With a smaller battery, or a bit better Tetris-ing of components, it could definitely be shrunk down a bit. But I'm pretty happy with how it turned out. I've been using it for a couple weeks now with my VMUPro and it's easily my favourite Dreamcast controller now.

I've uploaded the source code for the firmware to my GitHub if anybody wants to take a look or try their hand at building one themselves. The repository also contains the same Maple bus implementation used in Pico2Maple so could serve as a nice starting point for anybody wanting to try interfacing with the Dreamcast and it's peripherals.


Tags:


Pico2Maple - Sega Dreamcast Controller Adapter using Raspberry Pi Pico 2

Pico2Maple prototypes powered on during Power Stone 2.

Since getting the Steam Controller working on the Sega Dreamcast, I've been expanding the idea into a general-purpose USB-to-Dreamcast device with an eye on potentially selling it as a product. To that end, I've created a few prototype devices of something I'm calling Pico2Maple.

Pico2Maple is a dongle that plugs into the Dreamcast and allows USB devices to be used on the system in place of original Dreamcast peripherals. Several controllers, keyboards, and even some mice are supported (yes the Dreamcast had an official keyboard and mouse). Additionally, Pico2Maple emulates a VMU - the Dreamcast's memory card - complete with a tiny OLED screen and saving files to a microSD card for easy backups.

So far, I've confirmed the following controllers to work:

  • Steam Controller
  • 8BitDo SN30 Xbox
  • XInput controllers (Xbox 360, One, Series)
  • Sony DualSense5
  • 8BitDo Wireless Dongle (great for connecting a variety of other controllers wirelessly)

Most USB keyboards should work for games like Typing of the Dead or chatting in Phantasy Star Online. Mouse support does need a bit of improvement but chances are good most will work; it's hard to find enough hardware to test things like this.

Some USB devices will report multiple descriptors (a mouse may report as a mouse and a keyboard) for extra functionality. Pico2Maple will try and use the first valid device it sees and pass that through to the Dreamcast. Unfortunately, it's not possible to report multiple devices through a single Dreamcast controller port.

Pico2Maple prototypes.

The brains of the device is a Raspberry Pi Pico 2 with my custom firmware and Maple bus implementation. The firmware is not open source at the moment, but the binaries are available on my GitHub if anybody wants to make their own version of the hardware.

When I started working on this project, the RP2350 chip powering the Pico 2 was not readily available, so I designed a custom PCB where the Pico 2 board could be soldered directly to it. Since most of the 'real' electronics are on the Pico board, my PCB is more-or-less just a way to connect all the extra components and peripherals, with a form factor that would work well for a dongle.

Surprisingly, the prototype PCBs I ordered worked great! I must have gotten lucky because there were no functional issues with the boards. Due to the insane shipping times to where I live though, I was moving a bit fast and wasn't completely decided on a final design when I ordered the PCBs. This is why the USB port is facing the wrong direction and meant I had to do a bit of extra manual prep work on the boards. I hope to do a second revision to fix that, and move around a few components for a better overall fit.

Pico2Maple PCB render.

In addition to the custom PCB, this project was also my first experience with CAD and 3D printing. I designed the entire enclosure for the dongle in FreeCAD and printed them on a BambuLab P1S. The main body of the dongle is made up of 3 pieces that sandwich the electronics together and four m2 screws, with threaded inserts, extend through the whole dongle and squeeze everything tight.

It took quite a bit of tweaking a test-printing to get the fit I was going for but I think it was worth it in the end. They came out looking almost exactly like what I had imagined! (Wavebird dongle vibes anyone?)

The final dimensions of the dongle are roughly 30mm wide, 25mm deep, and 61mm tall. I would say they are a smidge too wide and are therefore a bit too snug when multiple are plugged in. The microSD card also sticks out about 1-2mm so, even though four can fit in the console by themselves, not all would be able to have SD cards plugged in. Ideally I'd shave off maybe 2mm from the width and have the microSD cards be flush for a better fit.

Other than being a bit too wide, I think the rest of the dimensions are perfect and they look pretty slick when plugged into the Dreamcast.

A Dreamcast-coloured Pico2Maple powered on.

I mentioned earlier that I hope to produce and sell these to fellow Dreamcast enthusiasts but the current road block is that assembly simply takes way too long to make it worth it. Between soldering the Pico to the main board, wiring up the Dreamcast plug, and final assembly, the whole process takes maybe 45-60 minutes which is too long for me. Plus I don't really like being hunched over a soldering iron for so long.

I could save some time if JLCPCB could presolder the Pico 2 boards for me, or if I could design a PCB using the RP2350 chip directly. But that still leaves wiring up the Dreamcast plug which is what really takes the bulk of the time, trimming wires and soldering the pins. I'd guess it would still take around 30 minutes to put one together which still seems too long.

If anybody has any tips on speeding up manufacturing I'd leave to hear it. I would also be open to potentially licensing the firmware and letting somebody else handle the manufacturing. Either way, feel free to reach out!

Thanks for reading!


Tags:


Using the Steam Controller on the Sega Dreamcast with Raspberry Pi Pico 2

Pi Pico 2 with Steam Controller and dongle next to a Dreamcast.

I've been scratching my head to come up with a project to play around with the Raspberry Pi Pico's PIO (programmable input/output) and eventually had the idea for some sort of converter to use non-Dreamcast peripherals on the Dreamcast. Of course, all good ideas have already been done, in this case not once or twice, but three times as far as I'm aware, and probably more.

All of these projects are based on the RP2040 chip (original Pico), while I wanted to make use of the new RP2350 (Pico 2) chip. In particular, there is a new PIO input masking feature available on the RP2350 which I think makes for a better implementation for reading the Dreamcast's Maple bus. Also, none of the previously-listed projects actually allow me to use by beloved Steam Controller. All this to say that I really wanted to try things on my own.

The Maple Bus

The Maple bus is how the Sega Dreamcast talks to peripherals on the controller port. It's a two-wire protocol where each wire takes turns being the clock and being the data. Essentially when a wire goes low, it signals that there is data on the other wire (a 1 or a 0), it allows a bit of time to read the bit, before the appropriate wire goes high in preparation for another falling edge.

Below is a sample reading of the Dreamcast send a packet to a controller. In this particular case it's Command 0x01 which is a request for information about what the peripheral is capable of. Hopefully you can see that every falling edge represents one bit of data, read from the other wire. I hope to go into more detail about the Maple protocol in a separate blog post.

PulseView reading of the Dreamcast sending a Maple packet.

Reading and Writing with Maple

To actually read and write data to the Maple bus, the RP2350's programmable input/output (PIO) sounded like the perfect solution. PIO on the RP chips are like little tiny co-processors that can run at a fixed clock rate. Each PIO block has 4 state machines, each with a few registers, and access to a shared space of up-to 32 instructions from a very limited set of instructions.

I wrote two PIO programs, one for reading and one for writing, and both got close to the 32 instruction limit so I ended up using two of the three PIO blocks available on the RP2350. With four state machines in each PIO block, it should - in theory - be possible to read and write from up to four controller ports on the Dreamcast. Though I'm only using one at the moment.

To read the Maple bus, I configured the PIO to constantly check the value of the 2 data lines, waiting for the value to change due to a line going high or low. It takes advantage of the fact that the Maple bus only has data available during a falling edge, meaning a valid is read when the voltage on the wires either goes 11->10/01 or 10/01->00. The former is interpreted as a 1 and the latter as a 0. The PIO program then pushes this bit (eventually) back to the main C program where it can be interpreted.

Writing to the Maple bus was a lot more straightforward. A bunch of data is fed to the PIO which clocks out the start-of-packet signal then starts sending the data accordingly, before finishing with the end-of-packet signal when no more data is available in its buffer.

The next two images below show what the whole thing ends up looking like on the wire. The first packet, pictured below, is a request for data coming from the Dreamcast, and the second packet is the requested data being supplied by the Raspberry Pi:

PulseView reading of the Dreamcast sending a Maple packet requesting data from the controller.

The above packet is send by the Dreamcast and has a command code of 0x9, which is a 'Get Condition' command. It also has some included data (the pink bubbles) with a value of 0x00000001 which should be interpreted as 'Controller'. So, it's asking for the current status of the controller.

PulseView reading of the Pico responding to the Dreamcast with data.

This packet is sent by the Pico in response to the Get Condition command. It has a command code of 0x8 which says that this is a response packet with some data attached. The first 4 bytes are again 0x00000001 saying this is about the controller, then the remaining bytes describe which buttons are pressed and the current axis values of the joystick and triggers.

The whole request and response only takes about 125 microseconds or 0.125 milliseconds. But the controller state is requested about every 16.7 milliseconds, or once per frame at 60fps.

Getting Data from the Steam Controller

Getting USB data from the Steam Controller was surprisingly straightforward since the Pico SDK has TinyUSB as a built-in library. So, with that and the hid-controller example from the TinyUSB docs I was able to start getting the raw USB data quite quickly.

To interpret the raw data that was coming from the controller, I referenced Linux's hid-steam driver as it has mappings as to the meaning of specific bits and bytes sent by the Steam Controller.

Then it was just a matter of keeping track of what buttons are pressed, and sending that data to the Dreamcast via the Maple bus whenever it was requested.

The Second Analog Stick

It's not really a secret, but also not widely known that the Dreamcast supports 2 analog sticks. Very few games will even accept input from a second analog source; Quake 3 and Unreal Tournament are two games known to support it. So, to make full use of the Steam Controller, I wanted the right trackpad to emulate the second analog stick.

To do this, I started by sampling touchpad X,Y-coordinates from the Steam Controller to try and get a velocity of finger movement. Just taking a single change in X,Y from every poll of the controller was quite jittery and not a very pleasant experience. By keeping track of the last several readings, I was able to calculate the average velocity which gave much better results. I played around with a few values but found that 10 samples was generally enough for input to feel smooth.

Another component to a nice touchpad experience is inertia from a quick flick. Basically, input should continue in the last know direction for some time whenever a finger is lifted off the touchpad. I did this by taking the last calculated average velocity and feeding it into an easing - exponentially decaying - function. Again, this involved some experimentation to get a good feel. Eventually, I landed on a cubed decay that lasted 400 milliseconds. Putting a finger back on the touchpad will also stop the inertial movement so it really feels like flicking a trackball around.

Closing

This really wouldn't have been possible without the awesome Dreamcast documentation from Marcus Comstedt. I'm no electrical engineer so his explanations of the exact workings of the Maple bus were invaluable. He also happened to write the Maple bus decoder for PulseView which generates the nice little data bubbles under the logic analyzer readouts. This project would have easily taken twice as long without that. I highly recommend checking out his stuff if you are interested in knowing more about the inner workings of the Sega Dreamcast.

There's also a little video showing the controller in action below, playing some Sonic Adventure.


Tags: