Posted on Leave a comment

Notes on RISC-V Assembly Language Programming – Part 12

5 February 2025

I’m not giving up on the CH32X line just yet. I remembered last night that I do, in fact, have a CH32X035C8T6 development board in stock in the lab. This is the LQFP48 package, so no remapping need be done for the I2C lines.

The board is the “official” WCH CH32X035C-R0-1v2. It is largely similar to the other board with a smaller package, except is does have an extra push button mounted, labelled “S1/KEY”. The schematic, however, shows it connected to PA21/RSTN, so perhaps it can be configured as a reset button.

The first thing to do is to attach the WCH-LinkE device programmer. I built a custom cable to connect +5V, ground, SWCLK & SWDIO, TX & RX for USART1 and PA21/RSTN. I also connected LED1 to PA0 using an additional jumper.

Now to see if the default MRS2 application will blink the LED for me. And it does. It also prints a debug message on the serial console, so this verifies most of the wiring on the new programming cable.

Next I want to see if the “reset” button actually acts like a reset button, or if further configuration is required. It works! Well, that’s going to save me a bit of time.

And just to be sure, I’ll run the EVT example HOST_KM, making sure to change the ‘device’ setting to the C8 variant. Good news: it also works. It detected when I plugged in the i8 wireless dongle and responded to keypresses on the i8, as well.

Now on to hooking up the OLED module, which was where things became irksome yesterday. I was able to re-use one of the OLED module test cables from another project, so I didn’t have to build one from scratch.

To test the OLED, I need only send it the “DISPLAY ON” command. To get there, a few things have to happen. First I have to initialize the GPIO pins SCL/PA10 and SDA/PA11 correctly, then enable the I2C1EN peripheral clock, as well as some setup for the I2C peripheral itself.

I have created a new MRS2 project called C8-SH1106 in the CH32X035 folder to get the OLED up and working again. I hope that Future Me does not confuse this “C8-SH1106” with the one I wrote for the 203. I’m leaving most of the supplied software in place.

Initializing the GPIO pins has alerted me to the fact that the GPIO pins of the CH32X035 devices are different from the CH32V parts I have used previously. I had noticed before that only one ‘output speed’ configuration was declared in the EVT examples, that being 50 MHz, which ocrresponds to the fastest of the options for the other devices. I did not look to see if that was an oversight or omission in the EVT code at the time. As I was going to configure the pins as ‘alternate function, open-drain’ outputs, I see that this is not an option here. There is a mode for ‘alternate function, push-pull mode’, with a note, “I2C automatic open drain”. Well, that’s what we’re here to find out, I guess.

Enabling the peripheral clock for the I2C port using the vendor-supplied SDK is easy enough:

RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1, ENABLE);

I only had to refer the to RM to find out which bus the I2C peripheral was on before invoking the correct command.

Now ‘sending a one-byte command to the OLED via I2C’ sounds straight-forward, doesn’t it? Even assuming that both the GPIO pins and the I2C peripheral are all properly initialized, the process is far from straight-forward.

It’s obviously true that I2C, as a protocol, does work. And even though I have very specific examples of my own code that successfully works using these OLED modules, it never ceases to amaze me how complex the actual interaction can be when dealing with the bare metal.

Here is the outline of how to ‘send a one-byte command’ to the SH1106 OELD controller chip (after initialization):

Step 1: Wait for the I2C bus to be ‘not busy’.

It’s not complicated at all. There is a single bit in the STAR2 status register called, not enigmatically, ‘BUSY’. If this bit is set, the bus is busy. Wait your turn. If the bit is clear, the bus is not busy. Do as you will.

The vendor-supplied SDK has a function to get the value of a single status flag. You pass in the pointer to the peripheral and a bit mask identifying the flag you want. Since this chip only has one I2C peripheral, I’m pretty sure I’m sending the right value here: I2C1. Other chips have two I2C peripherals. This one has only one. The function call looks like this:

while(I2C_GetFlagStatus(I2C1, I2C_FLAG_BUSY) == SET) {
    // wait for bus to be not busy
}

I tend to split up while() loops across multiple lines as it makes it easier for the debugger to show me where it is, precisely. Additionally, it reminds me that there probably ought to be a timeout coded in there, so that this “forever loop” doesn’t hang the system. It can also just as easily be coded as:

while(I2C_GetFlagStatus(I2C1, I2C_FLAG_BUSY) == SET);

My home-grown code just reads the BUSY status bit directly:

while(I2C1->BUSY == true); // wait for bus to not be busy

Step 2. Generate a START condition on the bus.

Having determined, one way or another, that the I2C bus is ready for some traffic, we begin a transmission by setting the START condition. This creates a special condition on the bus that lets all the attached devices know that something is about to happen. To do this, all that is required is to set the START bit in the CTLR1 control register. The WCH SDK has a function to do this:

I2C_GenerateSTART(I2C1, ENABLE); // generate START condition

It simply sets or clears the START bit in CTLR1 based on the ENABLE or DISABLE parameter passed. My way of doing this is even simpler:

I2C1->START = ENABLE; // set the START condition

Doing this triggers a state change within the I2C peripheral. Before proceeding, you have to wait until the status bits line up in the requisite order. The SDK calls it:

I2C_EVENT_MASTER_MODE_SELECT

My code calls it I2C_STATUS_MASTER_MODE. In either case, it’s simply the combination of the BUSY, MSL and SB flags from the two status registers.

BUSY    STAR2, bit 1:  1 = I2C bus is now officially 'busy’
MSL     STAR2, bit 0:  Master mode (1) vs slave mode (0)
SB      STAR1, bit 0:  1 = start bit has been transmitted on the bus

When we have determined that these values all align, it’s time to move on to the next step.

[Breaking News] I just received an answer to my question about changing the base of the values in the Debug view for the registers. Just hover your cursor over the label (not the value) and a tool tip appears with all of the various formats. Why choose, you ask? Can’t we have them all? Yes! Yes, we can.

This is going to be a big help when I’m trying to identify single bits within registers in the future. It happens more than one might think!

Back to the step-by-step guide to I2C function. We’ve set the START condition on the bus, and we have to wait until this is reflected in the peripheral status bits. We can use the SDK function like this:

// wait for peripheral to enter master mode

while(I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_MODE_SELECT) == NoREADY);

The I2C_CheckEvent() function returns either READY or NoREADY. This just means that the bit pattern of status flags passed in as the second argument matches the current status bit in the peripheral’s status registers. We can proceed to the next step now.

Step 3. Send the device address and direction bit

Every device on the I2C bus has an address. It can be either 7 bits long or 10 bits long. The OLED module we’re using has a 7 bit address. It seems to be fixed at 0x3C on this module. The controller chip itself has an option for using 0x3D as the address, but the signal that controls that is not brought out to any sort of convenient spot on the module itself, so we’re kinda stuck with 0x3C.

The address that we want to communicate with is sent one bit at a time onto the bus, along with another bit that indicates if we’re wanting to write to (0) or read from (1) the device. The 7 address bits are scooched up to the top of the outgoing byte and the direction bit is tacked onto the end. So if you’re actually looking at the bus using a protocol decoder or logic analyzer, you might see 0x78 going out. That’s perfectly correct.

At this point, all we have to do is send the combined device address (shifted left one bit) along with the direction bit out onto the bus by writing to the DATAR register. The SDK has a function for that:

I2C_Send7bitAddress()

But all you need is to shove the shifted address and direction bit out the DATAR register.

// send device address for writing

I2C_SendData(I2C1, (SH1106_I2C_ADDRESS << 1) | I2C_WRITE);

Where I have previously #define’d the following values in the code:

#define I2C_WRITE 0
#define I2C_READ 1

#define SH1106_I2C_ADDRESS 0x3C

This does the needed shifting and combining of bits. My version of the code is predictably simple:

I2C1->DATAR = (SH1106_I2C_ADDRESS << 1) | I2C_WRITE; // send address to write

As before, we now need to wait until the sun and the moon and the status bits at night align in the proper way. The SDK refers to this combination as:

I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED

My previous code used:

I2C_STATUS_MASTER_TRANSMITTER_MODE

Either way, you’re looking for the BUSY, MSL, ADDR, TXE and TRA flags

BUSY    STAR2, bit 1:  1 = I2C bus is now officially 'busy'
MSL     STAR2, bit 0:  Master mode (1) vs slave mode (0)
ADDR    STAR1, bit 1:  Address sent and matched
TXE     STAR1, bit 7:  Transmit register is empty
TRA     STAR2, bit 2:  Data transmitted

And once you’ve seen these bits are all set, it’s time to actually start talking to the now-addressed OLED module.

Note that if, for whatever reason, the OLED module is not powered up and on the bus, then you’re going to wait a long time. The ADDR bit in STAR1 is only set when the addressed device ‘acknowledges’ the address as part of the protocol. No OLED, no ACK. Here is a really good place to put a timeout or some other code to handle the very real possibility of the OLED not being connected properly.

The ADDR bit is also a good way to write a ‘bus scanner’ program that loops through all the valid I2C addresses and sees who responds with an ACK and who doesn’t. The whole point of the I2C bus was to be able to connect several devices together and talk back and forth using a minimum number of wires.

So can we send the ‘DISPLAY ON’ command, already? No! We cannot. That’s not how one talks to a SH1106 OLED controlled chip.

First, we have to send a ‘control byte’. It only has two interesting bits in it. One is called the ‘continuation bit’ and the other is the ‘D/-C’ bit. If the D/-C bit is cleared (0), then the next byte is a command for the controller chip. If it is set (1), then it is data to be written to the display memory.

I use these values to indicate which bits are set or not in the control byte:

// SH1106 control byte

#define SH1106_NO_CONTINUATION 0x00
#define SH1106_CONTINUATION 0x80
#define SH1106_COMMAND 0x00
#define SH1106_DATA 0x40

Step 4. Send the SH1106 control byte

Since we only want to send a single command byte, we can populate the contol byte as:

I2C_SendData(I2C1, SH1106_NO_CONTINUATION | SH1106_COMMAND); // send control byte

Now we need to wait for this combination of status flags:

// wait for control byte to be transmitted

while(I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_TRANSMITTED) == NoREADY);

This is a combination of TRA, BUSY, MSL, TXE and BTF flags

TRA     STAR2, bit 2:  Data transmitted
BUSY    STAR2, bit 1:  1 = I2C bus is now officially 'busy'
MSL     STAR2, bit 0:  Master mode (1) vs slave mode (0)
TXE     STAR1, bit 7:  Transmit register is empty
BTF     STAR1, bit 2:  End of byte send flag

Step 5. Send the command

Finally, we can send the eight bits we’ve worked so hard to prepare for.

#define SH1106_COMMAND_DISPLAY_ON 0xAF

The code looks pretty familiar by now:

// send command to turn on display

I2C_SendData(I2C1, SH1106_COMMAND_DISPLAY_ON);

// wait for command to be transmitted

while(I2C_CheckEvent(I2C1, I2C_EVENT_MASTER_BYTE_TRANSMITTED) == NoREADY);

Step 6. Set the STOP condition

To finish a transmission (or end a reception), we set the STOP condition on the bus:

I2C_GenerateSTOP(I2C1, ENABLE); // set STOP condition

Since it’s just a single bit in the control register CTLR1, bit 9, we can just set it directly:

I2C1->STOP = ENABLE; // set STOP condition

Compile & run, and we are rewarded with a screen of random garbage. But it’s infitely more interesting than what it previously was.

But I wanted to get this all written out so that Future Me does not spend as much time scratching his head and wondering what was I thinking ??? when he looks at this code again next year.

And yes, that’s all “all” you need to do to get the OLED turned on and showing tiny dots. Never mind that the screen is both backwards and upside down. There are commands to fix that, too.

What’s really interesting to me at the moment, though, is that this is working at all, since there are no pull-up resistors attached to the bus lines. Also, I’m not sure exactly how fast the SCL line is wiggling at the moment. I told it 400 KHz, but have yet to verify that. I have been able to push these displays up to 1 MHz in the past. Tomorrow will be a good time to explore these ideas.

Posted on Leave a comment

Notes on RISC-V Assembly Language Programming – Part 11

4 February 2025

Setting up the OLED portion of the project should be easy, as I’ve already done this on the 003, 203 and 307 variants within this family of chips. There will be opportunities for improvement of some things, and perhaps a chance to add a proper frame buffer so as not to be so reliant on the page boundaries of the OLED controller chip.

First I have to connect the the target OLED module, a 1.3″ 128×64 module based on the SH1106 controller chip. It’s just power, ground and I2C clock and data.

Now I’ve forgotten what powers the CH32X035 on this development board. The chip can actually run on +5V as well as 3.3V. The “VCC” lines measure 3.6V using my oscilloscope. The supplied schematic is not much help, as it shows VBUS1 (assuming +5V from USB) and going into the linear regulator U2 and coming out as VCC/3V3. The chip itself only has a single power pin, but it is designated as VDD. I see no connection shown from VCC to 3V3 to VDD. I was, however, able to measure 3.54V on one side of C1, a 0.1uF decoupling capacitor next to U1.

So I think I’ll power the OLED from 3.3V for the time being. Next I’ll need to decide which of the, let’s see… one I2C ports to use. Well, that narrows things down considerably. There are some remapping options available, but only one port.

The DS shows the default mapping of SCL = PA10 and SDA = PA11. Unfortunately for me, these pins are only brought out on the largest packages, the LQFP48 and LQFP64. So some sort of remapping is going to have to occur.

The first remapping option brings out SCL on PA13 and SDA on PA14. Also not brought out on the QFN28 I’m looking at right now.

The second remapping option brings out SCL on PC16 and SDA on PC17. Now why does PC17 sound familiar? Yes, it’s the pin that the ‘Download’ button is connected to. Which also means that it’s the USB DP pin, with PC16 being the USB DM pin. So that one’s out, if we want to use USB at some point (foreshadowing: we will).

The third remapping option brings out SCL to PC19 (24) and SDA to PC18 (25). These are certainly brought out on the QFN28 package, but unfortunately, they are the SWCLK & SWDIO signals used to program and debug the device.

The fourth remapping option brings the I2C signals out to the USB pins again. The fifth remapping option brings them out to the SWCLK & SWDIO pins again.

Now in truth we will not need the SWCLK & SWDIO pins to be connected to the device programmer in the field. It’s also possible to provide a ‘window of opportunity’ after each device reset or power cycle where the SWD pins are, indeed, SWD pins, and then get re-programmed to be I2C pins. However, I am very reluctant to go that route as I have had, let’s say, unsatisfactory experiences when re-purposing device programming pins.

Now it’s entirely possible if unusually cruel and abusive (to me) to use a ‘software’ I2C implementation by bit-banging the signals. I don’t think I want to do that today.

Posted on Leave a comment

Notes on RISC-V Assembly Language Programming – Part 10

3 February 2025

I have sent a brief summary of the RM errata to WCH via their technical support submission page. As they are currently celebrating the Lunar New Year, I don’t expect an immediate response.

Referring to Reference Manual v1.8:

On p. 73, Section 8.3.2.2 External Interrupt Configuration Register 1 (AFIO_EXTICR1), the value for assigning PB pins to the EXTI inputs is incorrect.

Per the RM:

00: xth pin of the PA pin.
10: xth pin of the PB pin.
11: xth pin of the PC pin.
Others: Reserved.

But the correct value for PB is 01, not 10.

I have code to demonstrate this issue if you would like to see it.

The value for assigning PA is correct, but I have not tested PC.

So now on to a more informative HardFault handler, in the hopes that I will never need it. The interesting part of this is the formatted hexadecimal printing routine, usart_puthex. Previously, I had a hierarchy of puthex, puthex2, puthex4 and puthex8 routines, but this one does all that and offers optional ‘0x’ prefixing and a variable length of 1-8 characters, depending on what you need. I allocated a little more space on the stack and used that as a string buffer to place the characters after I converted the last 4 bits of the value to an ASCII hexadecimal digit, then shifted the value to the right by four bits, for as many digits as was requested.

I haven’t tested the usart_puthex function extensively yet, but it seems to do the trick.

So now the HardFault handler should print out a message in the format “HardFault 0x<mcause> @ 0x<mepc> [HALT]”, where mcause and mepc are the values of the CSRs at that time.

Now I just have to induce a HardFault on purpose to test it. I use the following code:

.word 0 # *** debug *** induce illegal instruction trap

In RISC-V, any instruction of all ones or all zeros is considered to be an ‘illegal operation’. My trap works, and prints this on the console:

HardFault 0x00000002 @ 0x00000140 [HALT]

Which is precisely correct. Since the upper-most bit of the cause is zero, the lower 31 bits constitute the exception code, which in this case is ‘illegal instruction’. The address corresponds exactly with the location of the bad code in the program.

The only problem with this solution is that since it relies on the USART to transmit a message, it can only effectively be of use for errors after the USART is initialized. One solution would be to check the USART1EN bit to see if USART1’s peripheral clock has yet to be enabled, and if it has, to then check the UE bit to see if the peripheral has been initialized, then proceed with the messaging. It captures the important CSRs at the beginning of the handler in any case.

Now it should be time to set up the OLED interface and USB controller to get the framework for this project fully underway.

Posted on Leave a comment

Notes on RISC-V Assembly Language Programming – Part 9

2 February 2025

So I’ve had some time to think about it, and I think I will spend a little more time trying to better understand what exactly is going on with whatever it was that I did yesterday to make the chip reset itself on every other keystroke. It’s a bit ironic, as the whole point of this particular tangent was specifically to reset the device.

I’m going to build in a lot more debugging information into the code to help understand this present weirdness and also to be in a better position in the future to deal with it when it inevitably happens again.

The first thing is to add some code at the very beginning:

# *** debug *** check CSRs for exception information

csrr t0, mcause # cause of exception
csrr t1, mepc # address where violation occurred
csrr t2, mtval # exception value
csrr t3, mstatus # status

Then I did a bunch of other stuff, but it didn’t help. What I eventually found out was that I had neglected to configure the EXTI to use PB0 as the input to EXTI0. The default was PA0. That’s why the system reset itself on the second keystroke, because that’s the one that turned the LED on (active low LED) and toggling PA0 would generate the EXTI interrupt, resetting the system. I was able to confirm this by omitting only the LED toggle function, and all worked as expected.

So I set the appropriate bits in the External Interrupt Configuration Register AFIO_EXTICR1 to indicate that PB0 should be routed to EXTI, and for some reason it still didn’t work. Then I remembered that the AFIO controller has to have its peripheral clock enabled just like everything else. Once I added that to the list of the of PB2 peripheral clocks to enable, then everything works as expected.

Now… where was I? Oh, yes: testing the fake reset button. It still doesn’t work.

This time it is because the RM is wrong. Here are the values it indicates on p. 74:

00: xth pin of the PA pin.
10: xth pin of the PB pin.
11: xth pin of the PC pin.
Others: Reserved.

The default is 00, and this was certainly working when PA0 was toggling the LED. It seemed a bit odd to me, yet certainly within the realm of possibility, that the port numbering would be 0, 2, 3, instead of 0, 1, 2. So I just randomly tried a 01 in there and it works.

So now I have an external reset button attached to my board. It’s a bit twitchy. I might add a debounce timer in there to smooth that out a bit.

As a side note, I already knew this should be possible, because I had already implemented this feature on my re-spin of the tinyCylon using the 003, which also does not make the reset signal available on the smallest package, the -J4. The original tinyCylon is based on the 8 bit Atmel (now Microchip) AVR in an eight pin package. It used the external reset pin as a ‘mode advance’ input. Every time the button was pressed, it would advance the device mode. It was just easier to emulate an external reset pin in software than to re-architect the code.

I’m just a little disappointed that it wasn’t some sort of mystrious HardFault condition that would require Much Deep Thought. I’ve still got a nice HardFault reporting function planned. It is going to feature a much more advanced numeric output routine than I’ve previously used, and will be an excellent opportunity to try out an actual data algorithm (gasp).

Posted on Leave a comment

Notes on RISC-V Assembly Language Programming – Part 8

1 February 2025

And the i8 battery is still running today. I’ve forgotten how many days it is since I started the experiment! So I guess the battery life is ‘long enough’ at this point.

Removing the USB dongle from the development board allows me to use the PC17 input and the attached push button just like a standard GPIO pin. I wrote a short program to check the status of the pin whenever a character was received from the USART, then print a 1 or 0 depending on if the button was pushed or not, and it delivers the expected results:

# read the status of the 'Download' push button connected to PC17

la s0, GPIOC_BASE
lw s1, GPIO_INDR(s0) # read input pins
PC17 = (1 << 17)
li s2, PC17
and s1, s1, s2 # isolate PC17 input
snez a0, s1
addi a0, a0, '0' # convert to ASCII
call usart_putc # *** debug *** print status of download push button

Note that I was unable to use the ‘andi’ immediate form of the logical AND instruction, because the constant value assigned to PC17 (1 << 17) was too large. So I loaded it into s2 and used that as the other source register for the instruction. I’m using the snez instruciton again to give me a one or zero result, then adding the constant value of the ASCII character ‘0’, which is 0x30, so that either an ASCII 1 or 0 is typed out to the console, in addition to whatever character is echoed.

Since the over-all goal of the project is to operate as a USB host, I’m thinking that I am just going to have to give up on my dream of using the ‘Download’ button as a reset button. However, I still think that it would still be a useful facility to add a reset button of some sort to this board. I will use PB0 as the alternate reset pin, as it is brought out next to a ground pin on the board headers. This allows me to easily add a pushbuttoon already attached to a two pin header. In a previous life, it was the power button for a PC case.

So I should go back to the GPIO initiailization code and add PB0 as an input with a pullup resistor enabled. In fact, I should go ahead and fill out all the rest of the GPIO initialization, as we’ve already touched all three of the available GPIO ports in some way. This will also include all the ‘extended’ configuration registers:

# configure GPIO

    # GPIOA:  0 = LED output, active low

la s0, GPIOA_BASE
sw zero, GPIO_OUTDR(s0) # clear all outputs
li s1, 0x88888882
sw s1, GPIO_CFGLR(s0)
li s1, 0x88888888
sw s1, GPIO_CFGHR(s0)
li s1, 0x88888888
sw s1, GPIO_CFGXR(s0)

    # GPIOB:  0 = reset button, 9 = MCO, 10 = USART1_TX, 11 = USART1_RX

la s0, GPIOB_BASE
#sw zero, GPIO_OUTDR(s0) # clear all outputs
PB0 = (1 << 0)
li s1, PB0
sw s1, GPIO_OUTDR(s0) # clear outputs, enable PB0 pull-up resistor
li s1, 0x88888888
sw s1, GPIO_CFGLR(s0)
li s1, 0x88888AB8
sw s1, GPIO_CFGHR(s0)
li s1, 0x88888888
sw s1, GPIO_CFGXR(s0)

    # GPIOC:  17 = Download button input

la s0, GPIOC_BASE
sw zero, GPIO_OUTDR(s0) # clear all outputs
li s1, 0x88888888
sw s1, GPIO_CFGLR(s0)
li s1, 0x88888888
sw s1, GPIO_CFGHR(s0)
li s1, 0x88888888
sw s1, GPIO_CFGXR(s0)

I’m also going to shut down the MCO output for now, as it tends to bleed over into all the other signals. This makes the system clock initialization pretty simple: write a zero to RCC_CFGR0:

la s0, RCC_BASE
sw zero, RCC_CFGR0(s0) # 48 MHz, no MCO

Then I modified the code to read and report on the push button status:

# read the status of the 'reset' push button connected to PB0

la s0, GPIOB_BASE
lw s1, GPIO_INDR(s0) # read input pins
andi s1, s1, PB0 # isolate PB0 signal
snez a0, s1
addi a0, a0, '0' # convert to ASCII
call usart_putc # *** debug *** print status of download push button

Since the bitmap for PB0 (1 << 0) or 0x00000001, is ‘short enough’ to fit in the immediate field of the andi instruction, I don’t have to load it into a separate register to apply the logical function. Just how short is ‘short enough’? Let’s look at the specification again:

https://github.com/riscv/riscv-isa-manual/releases/tag/riscv-isa-release-6f69218-2025-01-30

The answer to my question is 12 bits, from the specification section 2.4.1. Integer Register-Immediate Instructions, p. 26. So typically any value between 0 and 4,095 will work. Just realize that it will sign-extend the immediate value if bit 11 is a one.

So the button works as expect at this point (just a digital input; not yet a system reset) and prints a 1 when it is not pressed and a 0 when it is pressed. That means my input pull-up resistor is working as expected and all the other configuration so far is behaving as I wish it to.

So now to connect the push button and the system_reset code. This will be done by the External Interrupt and Event Controller (EXTI), which is part of the PFIC and described in Section 7.4 of the RM starting on p. 32.

The first thing we need to do is configure EXTI0 for being triggered on a falling edge by setting bit 0 of EXTI_FTENR. Then we enable EXTI0 by setting bit 0 in the EXTI_INTENR register. Since the reset switch is on PB0, it is channeled to EXTI0, as would any signal on PA0 or PC0.

In the same way that the first function is the most fun, so is the first interrupt. There’s so much to prepare to get htings going. EXTI inputs 0-7 are grouped into one interrupt, EXTI7_0_interrupt_ID = 20. I’m planning to use the ‘shortcut’ of the vector-table free interrupt mechanism on this device, so we need to put the interrupt ID and the address of the interrupt handler routine in the VTF registers of the PFIC. Then there’s some mumbo-jumbo dealing with CSRs to both configure the chip to use the VTF system as well as enable interrupts on a global basis.

I forgot that you have to also add in the ‘enable’ bit to the handler address when setting up the VTF interrupts.

Now something I’ve done has upset the chip. It starts out OK, but after you type the second character, the system resets. What’s even more strange is that it is setting the ‘illegal instructions’ exception in the mcause CSR. So now I have to figure out what I did and undo it.

Perhaps you recall the short list of possible interrupts I wanted to handle in this application? Well, if not, it’s in the log somewhere, but if you do go back and find it, you’ll see that the very first interrupt in the list is the ‘HardFault’ handler. I have found, from my various tinkering, that when things go too far off the rails, the system usually throws an exception and lets you know what the problem is, if you only know where to look for the clues it’s leaving you. Having an interrupt handler that deals with a HardFault exception is a good way to examine the mcause CSR and print out the interrupt or exception number, as well as the address where it happened. This is not hard to implement, but I’ll need to write a little more code and at this point I think it would be best to do it tomorrow.

Posted on Leave a comment

Notes on RISC-V Assembly Language Programming – Part 7

31 January 2025

So today I want to revisit the la vs li vs lui confusion that I am experiencing about how I’m initializing the stack pointer. Having thought that the matter was settled, I deleted the other ‘control’ instructions that I was using for comparison. Luckily for me, I jotted it all down in my previous notes, so it was there when I needed it. Here is the reconstructed version:

la sp, END_OF_RAM # initialize the stack pointer
la sp, 0x20005000 # *** debug *** for comparison
lui sp, %hi(END_OF_RAM) # initialize the stack pointer 
la t0, END_OF_RAM # *** debug *** for comparison 
la t0, 0x20005000 # *** debug *** for comparison 

And here is what it gets crunched down to after assembly:

la sp, END_OF_RAM # initialize the stack pointer
0: 20005137 lui sp,0x20005
la sp, 0x20005000 # *** debug *** for comparison
4: 20005137 lui sp,0x20005
lui sp, %hi(END_OF_RAM) # initialize the stack pointer
8: 20005137 lui sp,0x20005
la t0, END_OF_RAM # *** debug *** for comparison
c: 200052b7 lui t0,0x20005
la t0, 0x20005000 # *** debug *** for comparison
10: 200052b7 lui t0,0x20005

So I had noticed that the first three instructions all resulted in the same instruction, 0x20005137, while the last two gave me a puzzling 0x200052b7. And in the clear light of day I see that is not the catastrophe I originally thought it was, because they are not initializing the stack pointer, but the t0 register, for a comparison.

Just to be doubly sure, I debug the code a line at a time and watch the registers in real time. Again, I spy the stack pointer holding the mysterious value 0x20002800 before any of the code is executed in this debug session.

The first instruction does what I want, which, in this particular instance was what I told it to do. The second instruction also seems to work properly, but since there was no net observable change of state, I might want to introduce intentional intermediate values just to make sure that the correct value is really being re-written to the stack pointer. The third instruction follows the pattern, leaving sp standing at 0x20005000.

The fourth instruction sets t0 to decimal value 536891392, which translates to 0x20005000, so that’s good. The fifth and final instruction does the same.

So the only mystery remaining is why I forgot that I had intentionally introduced a wrinkle into the testing methodology without following up on it correctly. It helps to write things down.

All this work to understand how to succinctly initialize the stack pointer when I’m not even using it yet. That, I think, is about to change.

Now I can get on to the important business of creating not one but two fake reset buttons for the development board of a chip that has no external reset signal available.

So the plan is to use an external interrupt line to trigger a routine that initiates a self-reset of the chip. So I will start at the very end and write a short routine that resets the chip and then call it when the user types a particular key on the console. And to do that, I need to modify the present code to wait for a character to arrive from the USART, echo it and then check if the reset key has been pressed and jump to the reset routine if it has. It would also be nice if the LED continued to blink, if not all by itself then perhaps every time a character was received.

Right now the USART initialization code spits out a single ‘!’ character to show that the thing is working.

I have just discovered that the GNU assembler treats ‘//’ as the single-line comment pattern, in addition to ‘#’. The old-school /* comment */ format is also supported. I only saw this because MRS2, which evolved from Eclipse, will append ‘// ‘ (including a space) on selected lines of code then you press the command+/ keys, similar to control+/ on other OSes.

So I will create a function that toggles the LED, so that I don’t have to keep track of two peripheral pointers at once.

The first function is always the most interesting. I vaguely remember how to do this in RISC-V assembly. First you decrement the stack pointer by how many bytes of memory your function will need, then preserve any registers that you need to preserve for the caller, if any. Then you do whatever is appropriate for the function to do and then back out the way you came in: ‘pop’ any preserved values off the stack and then return the stack pointer to its original value.

Now this makes me start thinking about whether my use of t0/t1 in the initialization code was the best choice. Technically, since no functions were called and no interrupts were suspected, it didn’t matter which registers I used. But now that we’re entering the grown-up world of proper functions and accountability, perhaps I should switch over to the ‘saved’ registers, s0-s11. They are also known as:

x8  s0/fp   saved register 0, frame pointer
x9  s1  saved register 1
x18 s2  saved register 2
x19 s3  saved register 3
x20 s4  saved register 4
x21 s5  saved register 5
x22 s6  saved register 6
x23 s7  saved register 7
x24 s8  saved register 8
x25 s9  saved register 9
x26 s10 saved register 10
x27 s11 saved register 11

Note that s2-s11 are not present at all on the RV32EC devices, such as the CH32V003.

Again, this is only if I want to stay reasonably aligned with the published ABI, which I am under no obligation whatsoever to observe. I have zero intention at this point of ‘cooperating’ with any other software on this project, so I have the dizzying freedom to do as I think best. And what I think is best does tend to shift a bit over time.

For reference, here is the RISC-V calling conventions as codified from the source:

https://riscv.org/wp-content/uploads/2024/12/riscv-calling.pdf

There is one caveat to that statement, however. Both the QingKeV2 and QingKeV4 processors have a feature called Hardware Prologue and Epilogue (HPE). This described in the V2 PM in Secction 3.4, p. 14 and V4 PM p. 17. This mechanism is triggered by either an interrupt or an exception and saves and restores either 10 (V2) or 16 (V4) of the ‘caller saved’ registers to and from the stack.

The V2 decrements to stack pointer by 48 before the push and adds it back afterward. The V4 saves the list of registers to an internal stack in a single cycle, then restores them when appropriate.

V2 saved registers:

x1  ra
x5  t0
x6  t1
x7  t2
x10 a0
x11 a1
x12 a2
x13 a3
x14 a4
x15 a5

V4 saved registers:

x1  ra
x5  t0
x6  t1
x7  t2
x10 a0
x11 a1
x12 a2
x13 a3
x14 a4
x15 a5
x16 a6
x17 a7
x28 t3
x29 t4
x30 t5
x31 t6

Updating to the latest Processor Manual (PM) for the QingKeV2, V1.2, I am reminded of questions I have yet to solve, such as what is the EABI mode on/off option controlled from the Interrupt System Control Register (INTSYSCR), at CSR address 0x804?

There is a typo in the PM V4 in Table 1-2 RISC-V Registers, where registers x18-27 are referred to as a2-11, when they should be called s2-11. Oopsie.

I’m not 100% sure how I can leverage this hardware capability to my advantage yet, but it’s nice to know it’s there. How much should it affect my choice of working registers?

So I think I’m going to switch over to using s0/s1 for the initialization code and thenceforth into the future. So that seems to work OK, and I can now write a function to toggle the LED and call it from a loop and see what breaks next.

Here’s what the program looks like now with an endless loop that just calls the led_toggle function forever:

loop: # an endless loop

    call led_toggle # toggle the LED

    j loop # do it again

led_toggle: # toggle LED1 on A0

    # on entry: none
    # on exit: none

    addi sp, sp, -16 # allocate space on the stack
    sw s0, 12(sp) # preserve s0
    sw s1, 8(sp) # preserve s1

    la s0, GPIOA_BASE
    lh s1, GPIO_OUTDR(s0) # read present value of GPIO_OUTDR
    xori s1, s1, (1 << 0) # toggle bit 0
    sh s1, GPIO_OUTDR(s0) # write inverted value back

    lw s0, 12(sp) # restore s0
    lw s1, 8(sp) # restore s1
    addi sp, sp, 16 # restore stack pointer

    ret # return from function

It’s nice to leave a comment in the function as to what is expected on entry and exit. In this example, no arguments are passed into the function and no return value is expected.

Alas, TextEdit does not allow me to indent a block of text. I can do it in the MRS2 code editor, copy it to the clipboard and then un-indent it in MRS2, then paste it into TextEdit.

Note that I am allocating four words of space on the stack in preparation for saving the registers, when I only need 2 words. This is because the ABI says to allocate space on the stack in 16 byte (128 bit) blocks. Now the ABI is not the boss of me, but sometimes I find that I need one more register and having allocated a bigger-than-needed block comes in handy. It doesn’t cost anything in execution time.

Now I need a function to see if the USART has received any characters.

usart_rxne: # return USART1 RXNE receive register not empty status

    # on entry: none
    # on exit: a0[0] = USART1_RXNE

    addi sp, sp, -16 # allocate space on the stack
    sw s0, 12(sp) # preserve s0

    la s0, USART1_BASE
    lh a0, USART_STATR(s0) # read status register
    andi a0, a0, USART_RXNE # isolate RXNE receive register not empty status bit
    snez a0, a0 # set not equal to zero

    lw s0, 12(sp) # restore s0
    addi sp, sp, 16 # restore stack pointer

    ret # return from function

So since I am going to use the s0 register as the peripheral pointer to USART1, I preserve its current value on the stack. Setting s0 to USART1_BASE, I can read in the status register STATR and mask out all the bits except USART_RXNE, leaving only the status bit. Now this particular status bit happens to be in bit position 5, leaving either a zero (receive register is empty) or a 0x20 (receive register not empty). Using the pseudoinstruction snez, I effectively set bit 0 to a 1 or a zero, depending on the value in the register. This makes it easier for the calling function to interpret the results, i.e., true or false, than expecting it to know which bits means what in every kind of peripheral status register.

Now I can write another function to actually receive and return a single character from the USART, using the usart_rxne function to tell if there’s anything there yet or not. Now in truth it wold also be possible to structure this another way. I prefer to do it this way, as I might want to have a separate routine to tell if a key has been pressed, e.g., kb_hit().

Here is the code to reset the system:

system_reset: # reset the system

    # on entry: none
    # on exit: does not return

    la s0, PFIC_BASE
    li s1, 0xFA050000 # key 1
    sw s1, PFIC_CFGR(s0)
    li s1, 0xBCAF0000 # key 2
    sw s1, PFIC_CFGR(s0)
    li s1, 0xBEEF0000 | PFIC_RESETSYS # key 3 + system reset request bit
    sw s1, PFIC_CFGR(s0)

1:  j 1b # loop here until reset occurs

I don’t really know if the loop at the end does any good or not, but there’s no specification on how long it takes for the system reset to take hold. We don’t want any more code executing after this point.

I added some code to get a character from the USART and echo it back to the console, then check to see if it was a 0x00 character (control+space) that was received. If it was, it just jumps to the system_reset function. The code there just feeds the three key values to the PFIC_CFGR register, with the last key having the SYSRST bit set (bit 7). The SVD calls it PFIC_RESETSYS.

This seems to work. The chip seems to reset and print a ‘!’ character, then just echoes back anything else typed in, until you type control+space, then you see another ‘!’ appear. Also the LED is toggled after every keystroke, and gets reset to ‘on’ after a reset.

I added a usart_puts function to print a nul-terminated string via USART1. You can declare a constant text string to print like this:

announce_string: .asciz "G8-asm\r\n"

And the code to print it is this:

la a0, announce_string # announce
call usart_puts

So now all I have to do is to wire an external interrupt to trigger the system_reset code.

The fisrt target is the ‘Download’ button on the board. It is connected between Vcc and PC17. So I need to setup PC17 in the GPIO initialization section as an input with a pull-down resistor. I also have to enable the peripheral clock for GPIOC.

Enabling the GPIOC peripheral clock was easy. I just added the RCC_IOPCEN value to the list:

# enable peripheral clocks

li s1, RCC_USART1EN | RCC_IOPCEN | RCC_IOPBEN | RCC_IOPAEN
sw s1, RCC_APB2PCENR(s0)

Configuring PC17 is going to be a little different than all the other GPIO pins I’ve initialized so far. First of all, you might have noticed that its number (17) is out of the ‘normal’ range of 0-15 that most of the GPIO in this series as well as the STM32 devices share. So its configuration is handled through the USB PD periperhal. PC17 is also used as the USB-PD ‘PDM’ signal.

Further reading of the RM (always rewarding, even if not right away) reveals that there are a couple of ‘expansion’ registers for the higher-order GPIO bits, like our little friend PC17.

Ah, I have mis-read the documentation. It’s not the USB PD peripheral that’s connected to PC17, it’s the normal, regular, standard USB-DM line of the USB full speed device. As that is presently connected to the i8 wireless dongle, pushing the button is not going to be immediately detectable by my simple software techniques.

I don’t think it will be possible to use the ‘Download’ button as an alternative reset button.
What I do think is that I ought to think about it some more and get back to it tomorrow.

In other news, the i8 battery is still running.

Posted on Leave a comment

Notes on RISC-V Assembly Language Programming – Part 6

29 January 2025

The i8 battery is still chugging along.

I’m considering publishing these notes on my web site.

I’m also just now noticing that the resulting disassembly code does not match my expectations.

I posted the notes as separate days and need to go back and number them and add some clarifications as they are all titled, “Notes on RISC-V Assembly Language Programming”. Which is true, but there’s a lot of them now.

I have added “- Part n” to each of the five posts. I still need to add navigation links between the pages, although there are links to previous and next posts at the bottom of each page.

I also need to use a different text editor with word wrap for composing these notes that are intended to be published. Removing the hard new lines is tedious and error-prone.

So the next things to do are to figure out why the sp initialization is still not right and make a fake reset button using either the RST line from the WCH-LinkE or the ‘Download’ pushbutton.

30 January 2025

Re-reading the posted notes and finding many typos remaining. I’m going over them again and correcting them as necessary. It was mostly removing the hard new lines and only a few actual typographical errors.

The i8 battery is still up!

I would like to make WCH aware of the problems I have been having when resetting the PWR control peripheral. How to get their attention?

I have made a copy of this file to perform some scientific experiments upon. Still using BBedit, I have used the Text / Remove Line Breaks command and it has done so. However, it is not wrapping the text at 80 columns so now I have a lot of really long lines that I cannot see all at once.

I just selected the View / Text Display / Soft Wrap Text and it seems to have done it. Now I will just continue writing a bit and see if what I think is supposed to be happening is actually what is happening. So this part looks good, but I have to go back and take a look at what it has done to the previously written manuscript.

It only really messed up my indented lists. Going forward, it should not be that much of a problem and should really expedite the publishing task.

BBedit does not remember the Soft Wrap text option between invocations, so I am shifting over to TextEdit, which comes with macOS. The right tool for the job!

Posted on Leave a comment

Notes on RISC-V Assembly Language Programming – Part 5

28 January 2025

Today I was able to reach wch-ic.com. wch.cn and mounriver.com. No telling if it had anything to do with the approaching Lunar New Year as celebrated in China and many other parts of the world or not.

I have taken the opportunity to upgrade to the latest CH32V003 RM V1.7, dated 2024-03-11.

So now I’m back to wondering why the GNU RISC-V assembler treats pseudo-instructions differently based on the destination register involved. Specifically, why does it it produce this:

la sp, _eusrstack # initialize the stack pointer
0: 20005117 auipc sp,0x20005
4: 00010113 mv sp,sp
la sp, 0x20005000 # *** debug *** for comparison
8: 20005137 lui sp,0x20005
lui sp, %hi(_eusrstack) # initialize the stack pointer
c: 20005137 lui sp,0x20005
la t0, _eusrstack # *** debug *** for comparison
10: 20005297 auipc t0,0x20005
14: ff028293 addi t0,t0,-16 # 20005000 <_eusrstack>
la t0, 0x20005000 # *** debug *** for comparison
18: 200052b7 lui t0,0x20005

So one thing I see is that when I reference the linker variable _eusrstack, it always uses the auipc+mv combination, whereas when I use the immediate value 0x20005000, it uses the single instruction lui (load upper [20 bits] immediate).

I don’t know if it has anything to do with anything, but it now feels like the time has come to deploy my own linker script. Not to worry, it’s already written and around here… somewhere.

I found four of them, for the 003, 203, 208 (just a copy of the 003) and 307. I’ll use the 307 as a basis and make a few changes, as appropriate.

Now here’s an issue I had not previously considered. The 003 only offers one memory configuration: 16KB flash ‘rom’ and 2KB SRAM. So a single linker script applies to the entire family.

It turns out that this is also the case for the CH32X035 line, all the way from the smallest (F) to the largest (R) packages offered: 62KB flash ‘rom’ and 20KB SRAM. So for today I don’t need to figure out how to accurately specify memory capacities in linker scripts for the larger parts, such as the 203, 208 and 307. [TODO]

OK, today’s tangent is to find out why or how the CH32X035F8U6 device in QFN20 package offers 19 GPIO. I have a stack of these as realized as the WeAct core boards.

Well, it’s true! They are using the bottom pad as the single, only solitary ground reference connection. This is also the case for the CH32X035G8U6 device that I am currently examining.

I’m not sure how I feel about this. Mostly, I’m glad this tangent was so quickly ended.

Note: Just make really sure to properly ground these parts when laying out a PCB. This effectively rules out their use on single-sided PCBs.

Small changes to the linker script:

Update header and footer with current date and new filename
Change ENTRY(start) to ENTRY(_start)
Adjust flash and RAM sizes as needed

Now it’s time to change the project settings to use the newly-available linker file, which I have added to the CH32X035/lib folder.

The MRS2 build options seem to expect the linker script to reside within the project folder, which is how it was and was working just fine. The two options for the linker script in the ‘Open the file from:’ option were Project or Local Folder. I’ll try a relative reference in the Project option first: ../inc/CH32X035.ld

Well, it didn’t like it: “ld: read in flex scanner failed”

But nowhere do I see a reference to the linker script in the command line invocation. Now the sharp-eyed amongst you will have seen my (now) obvious error: I referenced the ‘inc’ folder, not the ‘lib’ folder.

Once again, it needed an addition level of redirection, because the source code is within a project sub folder, so the proper entry is “../../lib/CH32X035.ld” in the linker settings.

Now it is rightfully complaining about an “undefined reference to `_eusrstack'”. So I will make the proper adjustment, substituting ‘end_of_RAM’ for ‘_eusrstack’ and see what happens.

Hey, it works. Waddaya know? Also, the mysterious ‘2048’ bytes of BSS are gone from the size totals summary, as they were a nod to the 2K allocated to the stack in the original linker script.

To get an assembler listing that includes the source code but does not include a lengthy list of all the defined symbols (there are a LOT of them from the include file), use these options:

NOT the 'Generate assembler listing..." from Assembler/Misc
NOT the 'Generate assembler listing..." from Compiler/Misc
Only these three (3) from  GNU RISC-V Cross Create Flash Listing/General
    Create extended listing
    Display source
    Disassemble

A very tidy listing, indeed.

Note: Leave some sort of debugging information available, i.e., don’t use Debugging: None option, or guess what? It won’t let you debug! I mean, it does, but doesn’t show you where you are at the moment as you step through the code.

So that was a nice step in the right direction. I can now delete the ‘Ld/‘ project sub-folder and the provided linker script, and the project still builds, flashes, runs and debugs as expected.

So the behavior of the assembler remains the same: the references to the ‘end_of_RAM’ value from the linker script are treated as addresses and handled one way while providing explicit immediate values are handled another way.

Adding the PROVIDE() function to the end_of_RAM variable makes no difference:

PROVIDE(end_of_RAM = ORIGIN(RAM) + LENGTH(RAM));

It worked without it, so I’m leaving it out for now.

So here is the linker script as it stands at the moment:

/* filename: CH32X035.ld
   linker file for CH32X035
   28 January 2025 - Dale Wheat */

ENTRY(_start)

end_of_RAM = ORIGIN(RAM) + LENGTH(RAM);

MEMORY {
    FLASH   (rx)    : ORIGIN = 0x00000000, LENGTH = 62K
    RAM     (rwx)   : ORIGIN = 0x20000000, LENGTH = 20K
}

SECTIONS {
    .entry  : { *.entry . = ALIGN(4); } >FLASH
    .system_vector  : { *.system_vector } >FLASH
    .device_vector  : { *.device_vector } >FLASH
    .start  : { *.start } >FLASH
    .main   : { *.main } >FLASH
    .text   : { *(.text*) *(.rodata*) . = ALIGN(4); } >FLASH
    .data   : { start_of_data = .; *(.data*) *(.sdata*) . = ALIGN(4); end_of_data = .; sidata = LOADADDR(.data); } >RAM AT>FLASH
    .bss    : { start_of_bss = .; *(.bss*) *(.sbss*) . = ALIGN(4); end_of_bss = .; } >RAM
    .noinit (NOLOAD) : { *(.noinit*) } >RAM
}

/* CH32X035.ld [end-of-file] */

There are some reasons for the way things are in this script, especially in the SECTIONS section. First, my bizarre way of thinking created a solution for sometimes having and sometimes not having a vector table at the very beginning of memory. This involves having a dummy slot reserved at the very first location, i.e., address 0x00000000, that is either a jump over the table, if it exists, or nothing if no table is present. In reality, at the moment, the first two 32 bit slots are ‘reserved’ and could be used for some sort of very terse initialization code, for the vector tabled applications of the future.

That all alludes to the ‘.entry’ section. Next would normally come the .system_vector and .device_vector segments, should they be required.

Now the really sneaky parts come into view. The .start segment contains the _start ‘function’ which is, in a C language program, a ‘naked’ function that does some initialization and then ‘falls through’ to the .main segment. This begins the start of the main() function of a normal C language program. Otherwise, the next segment defined is the .text segment where I put variously sub-segmented components, such as (from the converted include file):

.text 0 # needs to be at address 0

    j start

.text 10 # system vectors
.text 20 # device vectors

This mechanism helps make sure all the pieces fall in the right order when linked.

I promise the ‘cleverness’ ends there. I’m not a fan of ‘cleverness’ in computer code.

Back to unravelling the mystery. I already have a solution but I’m not liking it enough to let it go.

I need to convert the ‘address’ of the end_of_RAM ‘symbol’ into just a scalar value.

My feeble attempts to locate an answer on the interwebs has left me quite dissatisfied. Now I am thinking that there has to be another method to convey this information that we already know and does not change into a stylistically acceptable mechanism.

Does the SVD contain the extents of the memory? No, it does not.

So I have decided to hard-code the value in the device include file like this:

# device memory extents

END_OF_RAM = 0x20005000

I could eventually add other memory values such as the beginning and end of flash, etc.

This produces the desired effect in the assembled output listing:

la sp, END_OF_RAM # initialize the stack pointer
0: 20005137 lui sp,0x20005
la sp, 0x20005000 # *** debug *** for comparison
4: 20005137 lui sp,0x20005
lui sp, %hi(END_OF_RAM) # initialize the stack pointer
8: 20005137 lui sp,0x20005
la t0, END_OF_RAM # *** debug *** for comparison
c: 200052b7 lui t0,0x20005
la t0, 0x20005000 # *** debug *** for comparison
10: 200052b7 lui t0,0x20005

Note: This won’t work on the 003 as it only has 2K of RAM so it ‘ends’ at 0x20000800, which cannot be loaded as a 20 bit immediate value. This won’t be a problem for some of the new -00x parts that have been announced, as they come with 4KB of SRAM.

Posted on Leave a comment

Notes on RISC-V Assembly Language Programming – Part 4

27 January 2025

Because this has happened before, I will archive the two project files from the confused project and compare them to a newly generated one.

So it seems that after you delete all the generated project files (except the linker script for now), any new source files that are added to the project must be located within a sub folder of the project, as placing them in the project folder itself produces an error. Then just clean the project and re-build it.

Also, to access the generated include files, you have to add ‘../../inc’ to the include directories command (-I) in the Project Properties -> C/C++ Build -> Build Settings -> GNU RISC-V Cross Assembler -> Includes dialog box.

OK, now that everything works again, I need to narrow down which bit I offended when I was trying to reset all the peripherals at once. This happened once before on a -003 project, but I don’t recall exactly which one.

It was the ‘F4-28BYJ-48.S’, where I used a CH32V003F4 to drive a small stepper motor:

# hard reset all peripherals

li t0, RCC_I2C1RST | RCC_WWDGRST | RCC_TIM2RST # just these bits - not RCC_PWRRST!
sw t0, RCC_APB1PRSTR(tp) # reset APB1 peripherals

li t0, 0xFFFFFFFF # all of the ones
sh t0, RCC_APB2PRSTR(tp) # reset APB2 peripherals

sw zero, RCC_APB1PRSTR(tp) # release APB1 peripherals
sw zero, RCC_APB2PRSTR(tp) # release APB2 peripherals

Note that the CH32V003 family only has reset registers for the APB1 and APB2 peripherals.

Looking for the latest reference manuals leads me to discover that the wch-ic.com web site is not responding at the moment. This is the english-language version of the Chinese language web site, wch.cn, which is also not working for me at the moment.

The -003 chips only have four peripherals that can be reset via the RCC_APB1PRSTR register:

0   Timer 2
11  Window watchdog
21  I2C 1
28  Power interface

It was the ‘Power interface’ module that sent everything crashing down when reset. There were no problems resetting the other peripherals.

I also seem to remember reading somewhere, but I can’t find it now, that you only had to set the bits in the reset registers and they would automatically reset themselves. This is most certainly not the case. The peripherals remain in a reset state until you write a zero back into the corresponding bit position.

Now on the CH32X035 chips, there are reset registers for the HB, PB1 and PB2 buses. It also has the same reset bits for the PB1 peripherals, in the same places. It also adds support for the additional peripherals offered, including TIM3, USART2, USART3 and USART4.

I will conduct a slightly risky experiment in terms of time required to recover if I’m wrong by eliminating the PWR reset bit from my initialization routine and see if it bricks. It seems to work! Here is the adjusted reset code:

# reset all the peripherals

li t1, 0xFFFFFFFF # all of the ones
sw t1, RCC_AHBRSTR(t0) # reset HB peripherals
sw t1, RCC_APB2PRSTR(t0) # reset PB2 peripherals

li t1, ~RCC_PWRRST # everything but RCC_PWRRST
sw t1, RCC_APB1PRSTR(t0) # reset PB1 peripherals

sw zero, RCC_AHBRSTR(t0) # release HB peripherals
sw zero, RCC_APB1PRSTR(t0) # release PB1 peripherals
sw zero, RCC_APB2PRSTR(t0) # release PB2 peripherals

Instead of only setting the actual bits in the PB1 reset register, I set all of the bits except for PWRRST. Nothing terrible happened.

I tried to ask the MRS2 folks a question via the ‘Feedback’ option, but it failed with a timeout. It seems we’re having a hard time talking to China today. The question was how to change the numerical bases in the Debug Variables/Register view.

Posted on Leave a comment

Notes on RISC-V Assembly Language Programming – Part 3

26 January 2025

Where is the SVD file for the CH32X035 chips? I have found it within the MRS2 application itself:

/Applications/MounRiver Studio 2.app/Contents/Resources/app/resources/darwin/components/WCH/SDK/default/RISC-V/CH32X035/NoneOS/CH32X035xx.svd

The original file is dated 23 December 2024.

I have copied it to my CH32X035 project folder:

/Users/dalewheat/Documents/Projects/RISC-V/CH32V/CH32X035/CH32X035xx.svd

Let’s run my existing svd2inc.py script on it and see what breaks first.

Perhaps it would have been better to copy it to my Python project directory, instead. I’m not fluent enough in the Python to be able to run scripts from just anywhere, just yet.

/Users/dalewheat/Documents/Projects/Python/CH32X035xx.svd

I’m just a little surprised that it ran with no issues. It produces the following output to the console:

svd2inc.py - SVD to RISC-V ASM header file converter
SVD filename: CH32X035xx.svd
Parsing CH32X035xx.svd... done
Creating 'CH32X035xx.svd.inc'

Peripherals
PWR/PWR, 0x40007000, Power control
RCC/RCC, 0x40021000, Reset and clock control
GPIO/GPIOA, 0x40010800, General purpose I/O
GPIO/GPIOB, 0x40010C00, derived from GPIOA
GPIO/GPIOC, 0x40011000, derived from GPIOA
AFIO/AFIO, 0x40010000, Alternate function I/O
EXTI/EXTI, 0x40010400, EXTI
DMA/DMA, 0x40020000, DMA controller
IWDG/IWDG, 0x40003000, Independent watchdog
WWDG/WWDG, 0x40002C00, Window watchdog
TIM/TIM1, 0x40012C00, Advanced timer
TIM/TIM2, 0x40000000, derived from TIM1
TIM/TIM3, 0x40000400, General purpose timer
I2C/I2C1, 0x40005400, Inter integrated circuit
SPI/SPI1, 0x40013000, Serial peripheral interface
USART/USART1, 0x40013800, Universal synchronous asynchronous receiver transmitter
USART/USART2, 0x40004400, derived from USART1
USART/USART3, 0x40004800, derived from USART1
USART/UART4, 0x40004C00, derived from USART1
ADC/ADC, 0x40012400, Analog to digital converter
DBG/DBG, 0xE000D000, Debug support
USBFS/USBFS, 0x40023400, USB register
FLASH/FLASH, 0x40022000, FLASH
PFIC/PFIC, 0xE000E000, Programmable Fast Interrupt Controller
AWU/AWU, 0x40026400, AWU configuration
OPA/OPA, 0x40026000, OPA configuration
ESIG/ESIG, 0x1FFFF7E0, ESIG configuration
USBPD/USBPD, 0x40027000, USBPD configuration

Interrupts
2: NMI - Non-maskable interrupt
3: HardFault - Exception interrupt
5: Ecall_M - Callback interrupt in machine mode
8: Ecall_U - Callback interrupt in user mode
9: BreakPoint - Breakpoint callback interrupt
12: STK - System timer interrupt
14: SW - Software interrupt
16: WWDG - Window Watchdog interrupt
17: PVD - PVD through EXTI line detection interrupt
18: FLASH - Flash global interrupt
20: EXTI7_0 - EXTI Line[7:0] interrupt
21: AWU - AWU global interrupt
22: DMA_Channel1 - DMA Channel1 global interrupt
23: DMA_Channel2 - DMA Channel2 global interrupt
24: DMA_Channel3 - DMA Channel3 global interrupt
25: DMA_Channel4 - DMA Channel4 global interrupt
26: DMA_Channel5 - DMA Channel5 global interrupt
27: DMA_Channel6 - DMA Channel6 global interrupt
28: DMA_Channel7 - DMA Channel7 global interrupt
29: ADC1 - ADC global interrupt
30: I2C1_EV - I2C1 event interrupt
31: I2C1_ER - I2C1 error interrupt
32: USART1 - USART1 global interrupt
33: SPI1 - SPI1 global interrupt
34: TIM1_BRK - TIM1 Break interrupt
35: TIM1_UP_ - TIM1 Update interrupt
36: TIM1_TRG_COM - TIM1 Trigger and Commutation interrupts
37: TIM1_CC - TIM1 Capture Compare interrupt
38: TIM2_UP_ - TIM2 Update interrupt
39: USART2 - USART2 global interrupt
40: EXTI15_8 - EXTI Line[15:8] interrupts
41: EXTI25_16 - EXTI Line[25:16] interrupts
42: USART3 - USART3 global interrupt
43: UART4 - UART4 global interrupt
44: DMA_Channel8 - DMA Channel8 global interrupt
45: USBFS - USBFS
46: USBFS_WKUP - USBFS_WKUP
49: USBPD - USBPD global interrupt
50: USBPD_WKUP - USBPD_WKUP global interrupt
51: TIM2_CC - TIM2 Capture Compare interrupt
52: TIM2_TRG_COM - TIM2 Trigger and Commutation interrupts
53: TIM2_BRK - TIM2 Break interrupt
54: TIM3 - TIM3 global interrupt

Creating interrupt vectors
2: NMI_handler
3: HardFault_handler
5: Ecall_M_handler
8: Ecall_U_handler
9: BreakPoint_handler
12: STK_handler
14: SW_handler
Created 7 system vectors
16: WWDG_handler
17: PVD_handler
18: FLASH_handler
20: EXTI7_0_handler
21: AWU_handler
22: DMA_Channel1_handler
23: DMA_Channel2_handler
24: DMA_Channel3_handler
25: DMA_Channel4_handler
26: DMA_Channel5_handler
27: DMA_Channel6_handler
28: DMA_Channel7_handler
29: ADC1_handler
30: I2C1_EV_handler
31: I2C1_ER_handler
32: USART1_handler
33: SPI1_handler
34: TIM1_BRK_handler
35: TIM1_UP__handler
36: TIM1_TRG_COM_handler
37: TIM1_CC_handler
38: TIM2_UP__handler
39: USART2_handler
40: EXTI15_8_handler
41: EXTI25_16_handler
42: USART3_handler
43: UART4_handler
44: DMA_Channel8_handler
45: USBFS_handler
46: USBFS_WKUP_handler
49: USBPD_handler
50: USBPD_WKUP_handler
51: TIM2_CC_handler
52: TIM2_TRG_COM_handler
53: TIM2_BRK_handler
54: TIM3_handler
Created 36 device vectors
Created 43 vectors in total

It also produces a 153 KB file called CH32X035xx.svd.inc. The file has the following header:

# filename: CH32X035xx.svd.inc
# created by svd2inc.py on 2025-01-26
# based on CH32X035xx.svd

#   Device Name:    CH32X035
#   Vendor:         WCH Ltd.
#   Description:    CH32X035 View File
#   Version:        1.2

I will now create a ‘inc’ folder in the CH32X035 project folder, and put the new file there. I’m also frustrated that I still don’t know how to create a folder within a folder using the Finder application. It will create a folder at the root of whatever folder that you’re looking at, but not the one selected. Next time I will try to double-click on the desired sub-folder first, then within the new window or tab that is created, I will select File -> New Folder. [TODO]

Two things come to mind to check with this new SVD file:

Q1. Are there any 'enumerated values' defined?
A1. No.
Q2. Does the hard-coded STK definition of 64 bit counter still apply?
A2. Yes.

So now I need to create a generic CH32X035.inc file and have it subsequently include the generated file. I can also place the missing enumerated values that I will need in this file, as well.

Here are the definitions I wrote by hand for the G8-asm.S project:

# register addresses and field definitions

RCC_BASE = 0x40021000 # reset and clock control

RCC_CFGR0 = 0x04

RCC_HPRE_1 = (0 << 4)
RCC_HPRE_6 = (5 << 4)

RCC_MCO_SYS = (4 << 24)
RCC_MCO_HSI = (5 << 24)

RCC_PB2PCENR = 0x18

RCC_IOPAEN = (1 << 2)
RCC_IOPBEN = (1 << 3)
RCC_USART1EN = (1 << 14)

FLASH_BASE = 0x40022000

FLASH_ACTLR = 0x00

FLASH_WAIT_STATE_0 = 0x00
FLASH_WAIT_STATE_1 = 0x01
FLASH_WAIT_STATE_2 = 0x02

GPIOA_BASE = 0x40010800
GPIOB_BASE = 0x40010C00

GPIO_CFGLR = 0x00
GPIO_CFGHR = 0x04
GPIO_OUTDR = 0x0C

USART1_BPS = 115200

USART1_BASE = 0x40013800

USART_DATAR = 0x04
USART_BRR = 0x08
USART_CTLR1 = 0x0C

USART_RE = (1 << 2)
USART_TE = (1 << 3)
USART_UE = (1 << 13)

I should be able to swap in the newly-defined values from the include file.

I had to hard-code the include file into the build properties, as adding a relative reference, .i.e., ‘../inc’ did not work.

Alas, the SVD has not caught up with the new bus naming conventions. I was able to get the G8-asm.S project to assemble and it seems to run the same as before.

Now to add some more appropriate initializations and then put in some interrupts.

Unfortunately, the thorough reset I like to do for these chips has completely bricked the device. Here is the code:

# reset all the peripherals

 li t1, 0xFFFFFFFF # all of the ones
 sw t1, RCC_AHBRSTR(t0) # reset HB peripherals
 sw t1, RCC_APB1PRSTR(t0) # reset PB1 peripherals
 sw t1, RCC_APB2PRSTR(t0) # reset PB2 peripherals

 sw zero, RCC_AHBRSTR(t0) # release HB peripherals
 sw zero, RCC_APB1PRSTR(t0) # release PB1 peripherals
 sw zero, RCC_APB2PRSTR(t0) # release PB2 peripherals

I had the same problem with the CH32V003 chip. Now if I can only find out which peripheral it was that objected to the reset procedure…

There is a new ‘No-Reset Debug Tool’ that I haven’t seen before. It’s not unbricking the device, however. I was able to use the minichlink’s ‘unbrick’ command, and that reported success, but I was then still unable to erase the chip using ‘wlink erase’ or download with MRS2.

Wow, it was really bricked. The only thing that would work was to attach it to a Windows PC, connect via USB, hold down the ‘Download’ button while plugging it in, then running the WCHISP program (not available on macOS). Then I could download a blink program that set things right. I still had to run ‘wlink erase’ back on the MacBook to ‘unprotect’ the flash memory. Now it is working again.

In my flailing about with the MRS2 software I seem to have disabled the download function by selecting ‘Others…’ for the programming device. It replaced the usual dialog with just two lines, command and arguments. There does not seem to be any way to recover from this situation, so I’m just going to start over with a new project, saving the single source file G8-asm.S.