Posted on Leave a comment

Notes on RISC-V Assembly Language Programming – Part 19

14 February 2025

I spent some more time debating with myself about expanding my coverage of these lovely Hershey fonts to some of the other sets, but have decided for the moment to pause with the plain and simplex versions of the Roman set. These more than meet my immediate requirements for the present project and are nice to look at as well.

Now I need to go beyond plotting a single character in the center of the screen and write a little code to send them out to the screen in a more utilitarian manner. For now I’m going to use the ‘native’ resolution of 21 ‘raster units’ in height and see if I can get three lines of readable type on the screen at once.

Without scaling the fonts, the most I can get is two lines of text. But that is when I don’t accomodate the ‘tall bois’, like the ‘[‘ and ‘]’ brackets and , surprisingly, the lower case ‘j’. Expanding all the margins so that everything actually fits only allows a single line of text, sometimes with as few as 4 characters, for important messages such as “mmmm” or “—-“.

Revisiting the ever-so-fascinating statistics of a few days ago, we see where this is coming from:

Max width   30  613  m
Max x       11  613  m
Min x       -11 613  m
Max y       16  607  g
Min y       -16 719  $

Well, there’s our friend, the expansive ‘m’ and the other titans of the simplex set.

So now it’s time to scale the fonts and see if I can get a more useful number of characters on the screen at the same time and still have them be legible.

Posted on Leave a comment

Notes on RISC-V Assembly Language Programming – Part 18

12 February 2025

I can fit the scalar values for each glyph into a one-dimensional array. Then I need an array of pointers to variable-length arrays of coordinates. Others have been able to do all this with a single array, but I see a lot of wasted space in there.

I’m trying to decide ahead of time if I need to reproduce the left column and right column values in the representation array, or if I can just get away with character widths. Or do I even need to keep track of the character widths? I could just treat these as monospaced characters and just pick a number.

Here are the leftest and rightest columns from the plain set:

Max left = (-2, 9)
Min left = (-8, 1241)
Max right = (9, 1273)
Min right = (2, 9)

And here are the same statistics from the simplex set:

Max left = (-4, 509)
Min left = (-15, 613)
Max right = (15, 613)
Min right = (4, 509)

After I’m ‘done’ with these scalable fonts, there’s one more bit-mapped font trick I want to try. I can take my existing 5×8 font and double or triple it in size, giving a blocky character. That might better represent the types of letters and numbers seen on temporary highway signs, as those still tend to be composed of 5×7 (or so) LED matrices. But when am I ever ‘done’ with anything?

So I am going to assume that I need all this data for now, and incorporate it into some data structures and try to port them over to the project and see if I can plot some nice looking characters onto the little OLED screen.

The first array encodes the ASCII value of the character as the index, so that doesn’t need an actual slot in the data file. In reality, since the first 32 ASCII characters are technically unprintable, our array index [0] points to ASCII value 32, the space, which, ironically, while a ‘printable’ character, does not print anything. This offset is just something that has to be remembered.

Each entry in the array will be a typedef’d structure containing the requisite information:

Information         Plain       Simplex
------------------  --------    ---------
Number of vertices  (0, 38)     (0, 56)
Left hand column    (-8, -2)    (-15, -4)
Right hand column   (2, 9)      (4, 15)
Coordinate index

Note that these sampled data values only represent the two subsets, roman plain and roman simplex. Using any of the other styles will have different values. Just for completeness, here are the statistics for the entire occidental glyph set:

Statistic           Value   Character
------------------- ------  ---------
Max vertices        143     3323
Max left            0       197
Min left            -41     907
Max right           41      907
Min right           0       197
Max character width 82      907
Max x               41      907
Min x               -41     907
Max y               41      907
Min y               -48     2411
Max dx              40      796
Min dx              -29     2825
Max dy              78      2405
Min dy              -80     2411
------------------- ------
Total vertices      47,465

Just looking at the total number vertices, and remembering that each vertex will require a minimum of two bytes for storage, we see that this little device with its 62K of flash memory will not be big enough to render every one of these characters, without adding an external memory device of some sort. So for now, I’ll content myself with the plain and simplex roman variations.

The vertex encoding get tantalizingly close to a single byte per coordinate pair. However, I want to also encode the ‘pen up’ information, which I use to distinguish ‘move to’ and ‘draw to’ commands. If I felt like running histograms on these data sets, I might be able to see a further pattern or trend that would allow me to use a look-up table for these values. But I am going to leave that as an exercise for you, my Dear Reader. I have to draw the line, somewhere.

So it looks like our benefactor, Dr. Hershey, was on to something when he originally encoded his coordinates as pairs of single digits. I’m not going to use his precise technique, although it will still end up as 16 bits of data per vertex. I’m just folding in the out-of-band ‘pen up’ condition to each coordinate pair.

Reviewing the summary, it looks like our friend character 906 is bringing home all the gold medals. It’s the ‘very large circle’ glyph, and I’m going to disqualify it for being an outlier. This is the one that broke my Python script and simplistic transmission encoding. It’s a lovely pentacontagon, or fifty-sided polygon, and therefore the smoothest of the approximated circles in the repertory.

Statistic           Value   Character
------------------- ------  ---------
Max vertices        143     3323
Max left            0       197
Min left            -27     2411
Max right           24      2381
Min right           0       197
Max character width 46      992
Max x               22      906
Min x               -24     2411
Max y               39      2403
Min y               -48     2411
Max dx              40      796
Min dx              -29     2825
Max dy              78      2405
Min dy              -80     2411
------------------- ------
Total vertices      47,415

So for the vector array, each vector will be a typedef’d struct holding the x and y coordinates as signed integers, as well as a boolean ‘pen up’ flag to distinguish ‘move to’ from ‘draw to’. Since the x axis shows a slightly smaller range of values, I’ll squeeze the ‘pen up’ flag into the x side, perhaps like this:

typedef struct { // vertex data
    int         x:7;        // x coordinate
    PEN_UP_t    pen_up:1;   // 'pen up' flag
    int         y:8;        // y coordinate
} VERTEX_t;

So I’ll need to add some more to my little Python script to generate the data for these two arrays, then emit it in a close approximation of my C coding style.

It took a bit of fiddling and also some back-and-forth to get the data structures ‘just right’, but I was able to port over both the plain and simplex roman character sets and have them plot out on the OLED screen. One thing that tripped me up was the vertex count. The original definition file described a ‘vertex count’ that also included the left and right column data as an additional vertex. Also, it counted, as it should, the ‘PEN_UP’ codes. These two little deviations that I introduced into the True Form sure made things look weird on the little screen for a while. But I eventually realized the error of my ways and corrected the code. Now it runs through either the plain set or the simplex set with the greatest of ease. Drawing a single character at a time happens so quickly, it seems almost instantaneous. I’ll have to try printing out a whole screen of text and see if I can tell how long it’s taking.

Next I’ll need to see about scaling these ‘scalable’ fonts to fit my imagined sizes for the different formats I’d like to support. I also need to look at the big-blocky font I suggested previously.

Posted on Leave a comment

Notes on RISC-V Assembly Language Programming – Part 17

11 February 2025

Now I can focus on compacting the vector data for the glyphs I need for the project. But first, I have to identify them. This has already been done many times in the past by many people, but I feel that I have to do it myself. Unless I change my mind, which is something I can totally do.

A clever collection of interesting Hershey font information has been published by Paul Bourke:

https://paulbourke.net/dataformats/hershey/

Included in this archive, dated 1997, are two files, romanp.hmp (Roman Plain) and romans.hmp (Roman Simplex). These files contain the ASCII mapping data for the plain and simplex varieties, respectively.

The ‘plain’ subset consists of the smaller glyphs. There are no lower case versions (miniscules). The upper case (majiscules) is repeated in their stead. Some statistics I gathered from the plain subset include:

Statistic       Value   Character
--------------  -----   ---------
Max vertices    38      1225 {
Max width       17      1273 @
Max x           7       1273 @
Min x           -6      1246 ~
Max y           10      1223 [
Min y           -10     1223 [
                -----
Total vertices  764

These glyphs can be encoded with 4 bits for the x coordinate and 5 bits for the y coordinate.

The ‘simplex’ subset contains the larger glyphs, including upper and lower case, numerals and punctuation. They are also much more detailed. Here are the same statistics from the simplex set:

Statistic       Value   Character
--------------  -----   ---------
Max vertices    56      2273 @
Max width       30      613  m
Max x           11      613  m
Min x           -11     613  m
Max y           16      607  g
Min y           -16     719  $
                -----
Total vertices  1303

These larger glyphs can be encoded using 5 bits for the x coordinate and can almost squeeze the y coordinate into 5 bits… almost.

So far we’ve only been using absolute coordinates for these mappings. I wonder how much space we could save by using a relative distance from point to point? Start with an absolute coordinate and then just specify relative motion along each axis?

For the plain set, we get these statistics for relative distances:

Statistic   Value   Character
---------   -----   ---------
Max dx      10      809  \
Min dx      -12     1246 ~
Max dy      20      1223 [
Min dy      -20     1223 [

For the simplex set, we get these numbers:

Statistic   Value   Character
---------   -----   ---------
Max dx      18      724 -
Min dx      -18     720 /
Max dy      32      720 /
Min dy      -32     733 #

So the answer is no, the relative values have a greater range than the absolute values. I find this result entirely counter-intuitive.

Posted on Leave a comment

Notes on RISC-V Assembly Language Programming – Part 16

10 February 2025

The little Python script I wrote last night was able to open the ‘occident’ file of Hershey font descriptions and then import them into a list of lines. I then iterated over the list, line by line, extracting the character number, the number of vertices as well as the left- and right-hand extents of each of the characters, then write them to the console.

I added some more analysis to the script to get a better feel for the data. Each line can be a different length, as each character can have as many or as few strokes defined as it needs. The number of vertices should give me a clue to the actual length of the line. Since each vertex, which I’m just remembering includes the character extent pair as the first vertex, is exactly two bytes long, and the line header is fixed at 8 bytes, the formula:

vertices * 2 + 8

gives us the expected length of the line. This is the case except for these character numbers:

                                 Actual  Calculated
Number  Vertices Width           Length  Length
------  -------- -------------   ------  ----------
2,331   3        <-13,20>=[33]   214     14
3,258   4        <-10,11>=[21]   216     16
3,313   28       <-16,16>=[32]   264     64
3,323   43       <-16,17>=[33]   294     94
3,502   10       <-12,12>=[24]   228     28
3,508   12       <-12,12>=[24]   232     32
3,511   15       <-12,12>=[24]   238     38
3,513   7        <-14,14>=[28]   222     22
3,518   8        <-12,12>=[24]   224     24

And I see a pattern. Looking at the original data for character number 2,331, we have this very long line:

2331103EfNSOUQVSVUUVSVQUOSNQNOONPMSMVNYP[S\V\Y[[Y\W]T]P\MZJXIUHRHOIMJKLIOHSHXI]KaMcPeTfYf]e`cba RKLJNIRIXJ\L`NbQdUeYe]d_cba RPOTO ROPUP RNQVQ RNRVR RNSVS ROTUT RPUTU RaLaNcNcLaL RbLbN RaMcM RaVaXcXcVaV RbVbX RaWcW

It very clearly declares that there are 103 vertices, but my conversion resulted in a 3, so I’m obviously not pointing to the right segment of the string when extracting that value, missing out on the hundreds digit, for the very small number of characters that have over 100 vertices.

And that’s what it was. I incorrectly specified the ‘slice’ parameters of the vertex segment of the string. I am not very good at the Pythoning yet, but I am getting better.

So now I have some faith in the internal consistency of the data preserved lo these many years. Now I can move on to actually extracting the coordinate pairs from each string, knowing the exact moment that I should stop.

More Python trial and error has produced a working model that will output the coordinate pairs for each character, along with the ‘pen up’ commands.

Now I need to translate that into a series of simple commands that I can send to the OLED device via the serial link and have them drawn on the screen to visualize the characters.

I needed to install PySerial as a module so that Python can talk to the serial port:

python3 -m pip install pyserial

It installed pyserial-3.5.

The serial port available via the WCH-LinkE is found in the /dev folder as:

/dev/cu.usbmodemC0F98F0645CF2

I’ve got a good start on the Python script. It’s pushing out the coordinates both to the console and the serial port. I re-formatted the coding going out the serial port into ‘move to’ commands and ‘draw to’ commands. ‘Move to’ just updates the coordinates and ‘draw to’ actually draws the vector between the points.

As an intermediate stage, I was totally faking it by just drawing the endpoints of the vectors, and you could tell the overall shape of the character that way. I already had the point() function working, so that was an easy step. Adapting Bresenham’s line algorithm to the code was also staight-forward. It’s a delightful thought experiment and has been around longer than I have.

There are still some edge cases that bring them whole thing to its knees, such as character 907 and its -41 y-coordinate. I had added a +32 offset to the data points for serial transmission as a single byte, but that just didn’t work for our friend number 907. But I’ve seen enough of the characters drawn on the target OLED now to be sure that I want to go ahead and build these into the project.

Posted on Leave a comment

Notes on RISC-V Assembly Language Programming – Part 15

8 February 2025

It’s time to rename this series of posts, as I haven’t been using any sort of RISC-V assembly language at all in this project lately.

So now on to bigger and bolder fonts.

9 February 2025

So not a lot of work got done on the project yesterday, but I did have some time to think about it. And it occurred to me that bit-mapped fonts are great when they’re small but start to take up a lot of resources, i.e., memory space when they get bigger.

My mental arithmetic last night suggests that the biggest possible font on a 128 x 64 pixel display would be 64 x 64 pixels per character, giving a total of two characters on a single line of text. They would be perhaps a bit too squarish for my taste, so I could slim them down a bit and have 42 x 64 pixel characters, allowing up to 3 characters, but still only a single line of them. As I have defined 96 glyphs in my first font design for this project, I project that it would take 32K of memory space for just this one font. The target chip at the moment has 62K of memory available, so perhaps we’ve come up both a good minimum and maximum size for this display. As a point of comparison, the existing font that I have lovingly named font_5x8 takes up 480 bytes of memory.

Pondering further, a font sized to allow two lines of text would be 32 bits tall, 3 lines would allow up to 21 bits tall and four lines would divide nicely into characters 16 bits tall. It was at this point that it occurred to me that bit-mapped fonts were not the only way to go, especially on a resource-constrained device such as I’d prefer to use.

Another option are stroke or vector fonts. Instead of a predetermined array of ones and zeros are used to map out the appearance of the individual characters, a series of lines and perhaps arcs are described for each glyph.

A famous set of vector fonts was developed around 1967 by Dr. Allen Vincent Hershey. Like myself, he struggled with the age-old question of “but which font should I use?” as well as how to do so in an efficient way. These fonts are now referred to collectively as “Hershey fonts”. They use a relatively compact notation to describe a set of strokes between integer coordinates on a Cartesean plane, resulting in very legible characters.

Now while I smile quietly to myself for my efforts to give the world lower case characters with descenders, Dr. Hershey spent untold hours designing and transcribing characters in as many languages as he could find.

I found a copy of the original data file as part of an archive on:

https://media.unpythonic.net/emergent-files/software/hershey/tex-hershey.zip

Within this archive, a file called, simply, ‘occident’ contains a number of lines (1,610, to be exact), each defining the appearance of a single character. They are numbered from 1 to 3,926, as not all the characters are present in this file.

Now I would like to write a simple-ish program to plot these characters to the OLED module and see what they look like. This ‘program’ will be more of a system that has a portion that runs on my laptop and another that is running on the embedded device.

I’ll start writing the big-end of the system in Python and the little-end in C. The big-end will read in the data file in its entirety and convert the provded encoding into a series of ‘move to’ and ‘draw to’ commands for the OLED. So it turns out I’ll be needing those line generating functions, after all.

Posted on Leave a comment

Notes on RISC-V Assembly Language Programming – Part 14

7 February 2025

Now for some odd reason the display is not working at all today. Ummm, well, no, I’m wrong. It was working just fine. It was just displaying a screen full of zeros, as was right and proper for it to be doing. I was messing around with the screen initialization values, poking various bit patterns in to see where they showed up. Yesterday, the dots would show up in a random-seeming column. As I had not specifically programmed the column address, that was fine and to be expected. But today, oddly, the column pointer was randomly set to one of the ‘invisible’ columns: 0, 1, 130, 131. The SH1106 supports a 132 x 64 display, but this module has a 128 x 64 OLED attached. The designers decided to put it in the middle of the columns, starting with column 2. Again, fine and something that I was already aware of. But disconcertng when you think things are ‘going great’ and suddenly nothing works anymore.

One good thing about this diversion was that I had the opportunity to measure the screen update time to be ~24 ms, which gives an effective frame rate just over 40 Hz. So that’s not going to be the bottleneck that I thought it might be. I’m really not motivatated at this point to try to up the SCL frequency in hopes of a maximized data rate.

Because of the way the SH1106 wraps around from the end of a page to the beginning of the same page, it truly doesn’t matter where you start writing values, as long as you write 132 of them. If it’s all zeros, you can’t see any difference. If it’s a proper image, then it does matter.

The reason I was tinkering with the initialization values is that I had been experimenting yesterday with it and not being happy with the outcome. I eventually added a separate ‘clear screen’ loop that wrote zeros to all the memory and that did the trick. So instead of initializing the data in the frame buffer declaration as ‘{ 0 }’, which I thought would populate all of the elements with zeros, I just specifiy ‘{ }’, and the compiler treats it as ‘uninitialized’ and writes zeros in there for me.

Having a frame buffer for the display is nice. I no longer have to think about accessing the display’s memory buffer in pages and stacks of pixels. This allows me the freedom to think about designing glyphs in their appropriate sizes, not what is mathematically convenient.

I’d like to be able to use a Cartesian coordinate system to refer to the individual pixels on the display, in furtherance of my graphical ambitions. In one respect, half of the work has already been done for me, as the abscissa, also known as the x coordinate or column, maps directly to the index of an array I set up to represent the frame buffer. The ordinate, or y coordinate or row, has to be broken down into two components: the memory page index and a bitmask.

The frame buffer is built as an array of pages, with each page containing a three byte header and another array of 132 bytes. The three byte header contains the secret language of the SH1106 and allows me to just blast the entire 135 byte payload to the module and have it magically go to the right place within the OLED’s memory map.

Each page is defined by this typedef’d structure:

typedef struct { // data structure for holding display data with OLED header
    uint8_t     control_byte_1;
    uint8_t     page_address_command;
    uint8_t     control_byte_2;
    uint8_t     page_data[SH1106_WIDTH];
} SH1106_PAGE_t;

My frame buffer is just an array of these pages:

SH1106_PAGE_t SH1106_frame_buffer[SH1106_PAGES];

where I have previously #define’d various dimensions as:

// specific SH1106 module parameters are defined here

#define SH1106_WIDTH 132
#define SH1106_HEIGHT 64
#define SH1106_PAGES 8

Assuming we stay in Quadrant I of the Cartesean plane, arguably the best quadrant, with the origin (0,0) in the lower left corner, the x coordinate maps directly to the index of the page_data[] array. That part was easy.

The y coordinate is only a bit more complex. Given the range of 0-63 of possible y values, we can represent that with a 6 bit integer. The upper 3 bits determine the page number, which is the index into the frame buffer array, and the lower 3 bits identify a single bit within what I refer to as a ‘stripe’ in the SH1106 memory. It’s a short, vertical space, one bit wide and 8 bits tall. The lowest bit is the top-most spot within the stripe.

Now if we acted like we didn’t care, we could just take the three upper bits of the y coordinate and call that the page number. That would have the consequence of giving us a plane mirrored about the x axis, as page 0 is at the top and page 7 is at the bottom. We just need to subtract the upper 3 bits from 7 to get the right-side-up, happy Quadrant I orientation that I happen to prefer. So a little more complex, but not much.

So having now spelt this out in people jibber-jabber, it’s time to encode this into a series of mathematical transformations and some hopefully readable source code.

My first function will be the point() function. Technically, a point has no dimension, only a location. Our ‘points’ actually have a size of ‘one’ in both dimensions, but they do have a location that can be specified as offsets from the origin of our Cartesean coordinate system.

The parameters of the point() function should include the x and y coordinates as well as a ‘color’ value. Being a display of modest ambition, this OLED supports the binary options of ‘on’ or ‘off’. We can reporesent that as a one or a zero in the code.

I have taken the liberty of formalizing the available color palette:

typedef enum { // all the colors
    COLOR_OFF = 0,
    COLOR_ON = 1
} COLOR_t;

Now I am making an exective-level decision to have the graphics functions pretend that the display is only 128 x 64 pixels in extent. Perhaps this will save me some time in the future and keep me from looking for ‘invisible’ pixels that are there but hiding just off stage.

I will have to try to remember to update the display after these functions, as they only manipulate the contents of the frame buffer but do not actually communicate with the OLED.

So here is the point() function as it currently stands:

void point(uint8_t x, uint8_t y, COLOR_t color) { // plot a single point of color at (x,y)

    uint8_t page = (SH1106_PAGES - 1) - (y >> 3); // top three bits represent page number, reversed to be in Quadrant I
    uint8_t bit_mask = 1 << (y & 0x07); // bit mask of pixel location within display memory stripe

    x += 2; // move into visible portion of OLED screen

    if(color == COLOR_OFF) { // we'll reset a bit in the memory array
        SH1106_frame_buffer[page].page_data[x] &= ~bit_mask; // clear bit
    } else { // we'll set a bit in the memory array
        SH1106_frame_buffer[page].page_data[x] |= bit_mask; // set bit
    }
}

I realized later that I could just invert the top three bits of the y coordinate instead of subtracting them from ‘one less than the number of pages’. Either way seems equally obtuse.

And it works! Why am I always so surprised when anything does as expected?

Now to see how performant this little manifestation of my algorithm can be. I’ll write a loop that sets and then clears all the pixels, one by one. If it’s visibly slow, I’ll have to think about spending some time optimizing the process. If not, I’m not going to worry about it.

It’s pretty fast. It causes a brief flash on the screen, and then it goes blank again, all pretty quickly. There is a visible ‘tearing’ artifact across the bottom of the screen in this process.

Looking at the oscilloscope, I measure ~18 ms to write ones to the screen, and ~16.4 ms to write zeros. That’s a surprising difference. Given there are 8,192 indiviual pixels to be written, the setting function, including the loop overhead, is taking ~2.2us and the clearing function is taking 2us per pixel.

So it takes less time to set or clear all the pixels in the frame buffer than it does to send them to the display via I2C. Good to know.

Here is where, historically, I go nuts writing a bunch of optimized graphics primitives, such as vertical, horizontal and ‘other’ lines, filled and unfilled rectangles and circles, etc.

But for now I want to pretend to focus on actually finishing this project and resist the urge to write yet another library of functions that may or may not ever get used.

So now we will proceed to fonts or glyphs, as you prefer. The first one is always the most interesting. I’ve already got one that I like and will start there, but it was designed to be small and permit a larger amount of text on the screen at one time. One of the overall goals of this project is to make it at least somewhat visible and legible at a distance, so larger formats will be needed.

This brings me back to the need for a better font design tool. I’ve spent way too much time typing in ones and zeros and squinting at the screen while transcribing hexadecimal numbers. I have serached for a more appropriate tool that is already in existence but have yet to find anything that works within the constraints of this project. I feel yet another tangent coming.

Well, before embarking on the world’s greatest font design tool tangent, I’ll have to be happy with a tiny side quest. I noticed that to accomodate the discrepancy between the SH1106 memory and the physical OLED screen width, I had hard-coded a “+2” to the x coordinate in the point() function. The solution was to add a couple of new fields to the page structure to align with the ‘invisible’ columns on the left and the right side of the screen.

That part was easy. Modifying the dimension of the page_data member to not use what looks like (and totally is) another magic number, I had used a uint16_t as the requisite padding on each side, which is exactly two bytes long, then used the friendly-looking (not really) equation:

SH1106_WIDTH - (2 * sizeof(uint16_t))

as the number of elements. So it should still send out all 132 bytes of the frame buffer, but we don’t have to offset the x coordinate every single time. That saves about 20ns per pixel!

Now that’s fixed, I went back and checked the ‘single pixel at the origin’ test and noticed that sometimes the pixel seemed to travel along the bottom edge of the screen. That’s because nowhere was I setting the column address to 0, or to anything else, either. It was going to be whatever it happened to end up being. After a power on reset, the module is supposed to reset the column address to zero, and I’m sure it does. But I have updated the initialization sequence to specifically set the column address to zero. This is done in two steps, as there is a single byte command to set the lower four bits of the column address and another to set the four upper bits. Here is the new sequence:

uint8_t SH1106_init_sequence[] = {
    SH1106_NO_CONTINUATION | SH1106_COMMAND, // control byte
    SH1106_COMMON_REVERSE, // swap column scanning order
    SH1106_SEGMENT_REVERSE, // swap row scanning order
    SH1106_COLUMN_LOWER, // column address lower 4 bits = 0
    SH1106_COLUMN_UPPER, // column address upper 4 bits = 0
    SH1106_DISPLAY_ON, // command to turn on display
};

Now my little pixel is just where it belongs… or is it? Honestly, it’s pretty hard to see. One way to test this is to draw a single line rectangle around the edge or the screen and make sure all edges are visible.

Which reminds me that I am not checking the input arguments to the point() function. I’ll just do a quick test and silently return on out-of-bound values.

So I added a couple of quick argument checks to the point() function that just return on out-of-bounds values. Another option would be to simply mask off the invalid bits and look like we’ve “wrapped around” after passing the edge of the screen.

So the rectangle test shows that there is still room for improvement in my equations. It’s hard to describe, exactly, but it looks like each page starts writing a little to the right of the previous page, so that the ‘vertical’ lines are distinctly leaning.

One thing is for sure, and that’s that my bit mask formula is exactly backwards. In retrospect, I see it now. The larger the y value, the lower the bit position within the strip should be, not the other way. I replaced:

1 << (y & 0x07)

with:

0x80 >> (y & 0x07)

and the horizontal lines seem to be right on the edge of the screen now.

But each page is still scooched over one pixel to the right after the last page. This could be caused by sending out one too many bytes per page in the update function. As the function uses the reported size of the page structure as the byte count, it occurred to me that the compiler was padding the struct somehow. Adding the modifier ‘__attribute__((packed))’ to the struct declaration fixed the problem. This is not the first time that structure packing issues have created off-by-a-little-bit errors for me, especially in communication protocols.

Now my rectangle looks properly rectangular. Going back, I also check that the origin pixel is very decidedly in the lowest leftest spot. With just the right amount of background light, I can barely see the edge of the OLED grid.

Now I can import my existing, hand-crafted OLED font from another, similar project. The font is contained in a C source code file named ‘font_5x8.c’ from the previously-mentioned C8-SH1106 project for the 203.

Copying the bits out of the font definition array and writing them to the frame buffer works like a charm.

I put that code in a little loop to go through and print all the available characters, and it goes by a bit too quickly to be able to see what it happening. I added a short delay to the loop and it’s quite satisfying to see it working so well. Here is the code:

for(uint8_t glyph = 0x20; glyph < 0x80; glyph++) { // all the characters in the font file

    for(x = 0; x < 5; x++) { // columns
        for(y = 0; y < 8; y++) { // rows

            if(font_5x8[glyph][x] & 0x80 >> y) {
                point(x, y, COLOR_ON); // draw the pixel
            } else {
                point(x, y, COLOR_OFF); // erase the pixel
            }
        }
    }

    SH1106_update(); // let's see what happened
    Delay_Ms(250); // short delay
}

The Delay_Ms() function is provided by the boilerplate example project generated by the MRS2 software when asked to create a new project.

Posted on Leave a comment

Notes on RISC-V Assembly Language Programming – Part 13

6 February 2025

Today’s first objective is to capture and measure the SCL signal and see how close it gets to the requested 400 KHz that I specified in the I2C initialization function.

After attaching an extension cable in order to tap into the SCL line going to the OLED module, I measure a SCL signal trying so hard to wiggle at 423 KHz, which is almost 5% over what I specified. Again, it’s not a critical value, as I have successfully run these OLED displays at 1 MHz in the recent past.

Debugging the program, I can look at the I2C registers directly and see what has been set up for me. The CTLR2 has a field named FREQ, and it has been set to 48. This is in line with what the RM indicates should be done. The CLKCFGR has a field called CCR, for the clock division factor field, and it is set to 0x04.

The actual timing calculations are shrouded in mystery, at least from the standpoint of trying to understand what the RM says. My experimentation suggests that the FREQ field has zero effect on the SCL frequency, and that the CCR field alone sets the pace. It’s also dependent on whether or not you are using ‘fast mode’ or not, as well as the selected clock duty cycle.

Also worthy of note is that the waveform has a very slow rise time and quite abrupt fall time, as would be expected from an open-drain output with no pull-up resistor to help. I have a second OLED module set up with 1KΩ pull-up resistors installed, which is considered quite stiff in the I2C community. This module’s SCL line shows much sharper rise times. So I think that in the lab it’s OK to “get away with” no pull-up resistors for testing purposes, but any final product design should certainly incorporate them. Surface mount resistors are not expensive.

The first improvement I would like to make on the existing system is to use interrupts to pace the transmission and reception of data over the bus, instead of spin loops that may or may not be monitored for a time-out condition. There are two interrupts available for each I2C periperhal on these chips, one for ‘events’ and the other for ‘errors’. I’ll need to define a state machine that is set up before any communications and serviced by the two interrupt handlers.

I will also need to come up with a suitable API to be able to hand off various payloads to the display. While the OLED controller chip allows for both reading and writing, I am not immediately seeing a strong case for ever reading anything back. So I’m thinking that the majority of transfers will be writing some combination of commands and data to the display.

The first case is the initialization phase. Ideally, the screen memory needs to be either cleared or preset to a boot splash screen, followed by commands to adjust any operating parameters. The controller chip’s built-in power on reset sequence does almost everything we need as far as setting up its internal timing. We only need to flip the ‘on’ switch to see dots. But as I alluded to yesterday, the screen on this module is mounted upside down and backwards. While there is no single “rotate 180°” command available, there are two other commands that will do effectively the same thing. One reverses the column scanning order and the other reverses the row scanning order. So we’ll need to send those two commnds before we turn on the display. There’s also a setting called ‘contrast’ that might more accurately be called ‘brightness’ that defaults to spang in the middle of the range.

Unlike the other popular OLED controller, the SSD1306, the SH1106 does not automatically roll over to the next ‘page’ of memory once it gets to the end of the row. This means that the ‘screen fill’ task must be broken up into eight page fills. Each of these must be preceded with a page address command. So the initialization ‘payload’ begins to take shape:

Address page 7, fill with 132 bytes of some pattern
Address page 6, fill with 132 bytes of some pattern
Address page 5, fill with 132 bytes of some pattern
Address page 4, fill with 132 bytes of some pattern
Address page 3, fill with 132 bytes of some pattern
Address page 2, fill with 132 bytes of some pattern
Address page 1, fill with 132 bytes of some pattern
Address page 0, fill with 132 bytes of some pattern
Reverse column scan
Reverse row scan
Optionally set contrast level
Display on

I fill the pages in ‘reverse’ order so that it ends up addressing page 0, which seems the logical place to start in the next stage. It will save at most one page address command, so this trick might get axed to favor clarity over cleverness.

The SH1106, much like the SSD1306, is a simple matrix display controller and does not offer any sort of built-in text capabilities. We have to supply our own fonts, which translates into “We get to supply our own fonts”.

I had originally used a 8×8 font that was very easy to read, but ultimately went with a 6×8 font that was, to me, much nicer looking. I then spent a lot of time writing what I considered ‘optimized’ routines to place characters on the screen in what seemed a sensible manner. Mostly this had to do with working within the constraints of the memory organization of the controller chip’s display RAM. This resulted in feeling very much blocked in to using either 8×8 or 16×16 fonts.

What I’m thinking about doing now is very different. Instead of writing each character directly to the screen’s memory, I’m going to introduce an intermediate frame buffer within the CH32X035 memory space. It’s only 1,056 bytes if we map every display location, but only 1,024 bytes if we only map the visible 128 columns that are supported by the physical OLED screen of this module. Each byte contians, as you know, 8 bits, and each bit corresponds to a single screen pixel. There are no shades of gray; it’s either on or off.

So my ‘print’ and ‘plot’ functions will actually only write to an internal SRAM-based frame buffer, and when ‘the time is right’, the whole memory will be transferred to the OLED display. This could be aided by DMA and interrupts to help off-load some of this burden from the CPU.

So that’s my plan for completely over-engineering this project and multiplying the amount of effort required to get to the finish line.

A couple of little experiments to try before diving into the big stuff. I noticed in the SDK that the GPIO initialization for the I2C port used two separate calls to the GPIO_Init() function, one for each of the two I2C signals. The library can actually set up as many pins on a single port as you need. You just indicate the pins needing initiailization with a bitmap passed in as the GPIO_Pin structure member. So I was able to combine the two calls into one:

// configure SCL/SDA pins

GPIO_InitTypeDef GPIO_InitStructure = {0};

// GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
// GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
// GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
// GPIO_Init( GPIOA, &GPIO_InitStructure );

// GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11;
// GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
// GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
// GPIO_Init( GPIOA, &GPIO_InitStructure );

GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10 | GPIO_Pin_11; // PA10/SCL, PA11/SDA
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);

I also tried bumping up the SCL frequency to 1 MHz, via the I2C_ClockSpeed structure member passed to the I2C_Init() function. No dice. I don’t know why yet, but I might find out in the future. Right now it’s chugging along at over 400 KHz, and that should be fine for now. In theory, I should be able to push almost 38 frames per second to the display at this speed.

And now on to the Great Embiggening of the I2C API. First, I want to enable the available interrupts and get a feel for how and when they are triggered and then work around that.

The SDK provides a function to enable or disable the various combinations of available interrupts. There appears to be an additional type of event interrupt for when either the TXE or RXNE status bits are set, indicating space is now available for more of whatever was going on at the time.

Right now I just want to look at the event interrupts, then I will look into the error interrupts and once I get the DMA configured, I’ll have another look at the buffer interrupts.

Note that the I2C_ITConfig() function only enables the interrupts at the device level. It does not enable any interrupts at the system level.

To do that, we use the SDK function NVIC_EnableIRQ(). The argument to pass is the interrupt number, and it took a bit of sleuthing on my part to track it down. There is an enumerated type IRQn_Type in ch32x035.h that contains the values of all the interrupt numbers. The one we want right now is I2C1_EV_IRQn, which has a value of 30. I was able to find the value in the RM, but I much prefer to have a defined value referenced and not a “magic number”.

There is also a SDK function called NVIC_Init() that will let you either enable or disable an interrupt as well as set the Preemption priority and subpriority.

Note that the system-level global interrupts are enabled in the supplied startup_ch32x035.S file.

The SDK also defines labels for all the interrupts. The I2C interrupts are:

I2C1_EV_IRQHandler
I2C1_ER_IRQHandler

So at this point, I need to define a function for this interrupt handler. It also needs to specify that it is an interrupt handler, so it gets the proper signature and whatever else the compiler wants.

The first thing the interrupt handler needs to do is figure out why it was invoked. Going in order things we actually did, the first thing to look for would be the start bit SB in STAR1, bit 0 being set, indicating that a START condition was set.

I have seen the I2C event interrupt being triggered as expected. I added code to examine the status registers and respond accordingly. There are really only three condition of note.

1.  I2C_EVENT_MASTER_MODE_SELECT
2.  I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED
3.  I2C_EVENT_MASTER_BYTE_TRANSMITTED

The first happens after a START condition is set to indicate that the device has entered MASTER mode.

The second happens after the device address and direction bit have been successfully transmitted.

The third happens after each byte has been transmitted.

Additionally, and for no obvious reason, one more interrupt occurs after the STOP condition is set, even though the status registers all read zero. I choose to ignore this.

So I replaced the entire SH1106_init() function with a call to the new i2c_write() function, passing the SH1106 device address and both a pointer to and a length of an initialization sequence:

uint8_t SH1106_init_sequence[] = {
    SH1106_NO_CONTINUATION | SH1106_COMMAND, // control byte
    SH1106_COMMON_REVERSE, // swap column scanning order
    SH1106_SEGMENT_REVERSE, // swap row scanning order
    SH1106_DISPLAY_ON, // command to turn on display
};

So now the display should be neither umop episdn upside down nor backwards, as well as on. And it works!

Now I need to dive a little deeper into the SH1106 data sheet and try to understand the ways to send data and commands to the controller chip. I’m still a little fuzzy on how the ‘continuation bit’ works as far as sending larger packages of data and commands to module is supposed to work.

The next communique I would like to send to the module is a ‘page fill’ command. This is composed of a ‘page address’ command, from 0-7, followed by 132 of your favorite numbers.

I added a ‘state’ variable to the I2C API, as it exists now, so that it doesn’t clobber itself. This is possible, as starting the process is quick and the function returns immediately, but the transfer takes a small but non-zero amount of time to complete.

I had a bright idea to break up the page fill routine into sending a ‘preamble’ with the page address command preformatted, then send the data as a separate function call. This doesn’t work, because each call to i2c_write() is a self-contained thing, with its own START and STOP conditions. This does not seem to sit well with the SH1106.

I reformatted the frame buffer to actually have some space between the data rows to fit in the OLED commands, and this seems to be working fine. Right now I’m just zeroing out the memory and it clears the screen. Ultimately, I would like to have a ‘splash’ screen that shows up for a second when the device is first powered on.

So the first of my goals (using interrupts) has been realized. I’m debating the value of pursuing the DMA option at this point. I think I will spend some time trying to get some reasonable looking dots onto the screen, such as text and maybe some geometric graphics.

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.