Showing posts with label BCD. Show all posts
Showing posts with label BCD. Show all posts

Wednesday, January 5, 2022

2022 Project Goals

Though I haven't made many posts in the past two years, I have been working on projects slowly but surely. As time passes, I realize how important it is to focus on a small number of projects so that some of them eventually get finished. For 2022, I'd like to pick exactly which projects I want to finish. Hopefully this will motivate me and help me focus!


Main projects

6507 Graphing Calculator
This project is still going after 18 months of work. While I haven't made any progress on implementing the new firmware features I mentioned in my last post on this, I have been working a lot on a subproject for verifying the calculator's floating point routines. Like many projects, this took a lot more time than I expected. Hopefully, I'll be done with this subproject soon so I can post about it. I've also been working on a way to make nice plastic keys for the calculator.

PIC32 Robot
This is an idea I've had for a long time for a simple "robot" built using a PIC32 microcontroller. It's a really interesting project that shouldn't take nearly as long as the calculator projects. It will be a good opportunity to get familiar with PIC32s which I want to use for a future calculator project. Hopefully, I can devote a little bit of time to this and still have time to finish or at least make good progress on the 6507 Graphing Calculator this year.


Other projects

Tiny Calculator
Since the 6507 competition began in 2020, I stopped working on this calculator. In the unlikely event that I finish the 6507 calculator this year, I'd like to return to this project and make some major changes. First, the floating point routines need to be redone using proper guard, round, and sticky like I learned how to do for the 6507 calculator. The existing Tiny Calculator firmware doesn't round in a conformant way and instead uses 32 decimal places to try to mitigate the rounding errors. Also, the routines use 9's complement as TI shows in their documentation for BCD subtraction. It became clear after writing most of the firmware that this wasn't the right way to go, but I didn't have the heart to rewrite everything. My plan now is to take as much as I can of the existing firmware and write a library of BCD floating point functions that use 10's complement with 12 decimal places and proper rounding then call those functions from C to rewrite the Tiny Calculator firmware. I'd also like to find a better solution for the keys and case.

PIC32 Calculator
This is another project I have thought about for a long time. This should be much simpler to tackle than my other calculator projects since I won't be writing the firmware from scratch. If I'm able to finish my two main projects this year, this is another one I'd like to start working on.

Wednesday, April 17, 2019

Tiny Calculator: Hardware

Tiny Calculator is business card size.
The hardware for this project is finally done! The first step was getting the LCD running. This time I went with a 128x32 LCD from Newhaven, which is a little pricey at $11. A simple HD44780 compatible LCD like I used for my RPN Scientific Calculator project would give me the same 20x4 character resolution for $3-4, but all the ones I have seen are way too big. Another option would be a small OLED screen, which are very cheap but would drain the CR2032 battery a lot faster.

The LCD has 17 pins with 1.5mm spacing, which is smaller than a breadboard or protoboard but still big enough to solder by hand. The majority of the pins are for capacitors, so I soldered a small adapter board to hold them and route the data pins to a breadboard. This was tedious and more difficult than I imagine when I bought the LCD but the hardware worked on the first try. After I got it running, I epoxied the LCD to the board. Next time, I think I will go with something easier to solder like an OLED screen even if it takes more current.


The datasheet for the LCD has some initialization code, which I could not get to work. A search turned up some working C code from another forum that was easy to get running with GCC for the MSP430. Translating the C code to assembly was a little tricky since some of the variables for initializing the SPI module on the MSP430 are not plain constants as you might expect from looking at the C code. It took some searching in the header files to figure out that what appears to be a constant is actually something cleverly defined to load a configuration value from the MSP430. After I got that working, everything else went smooth. Rather than try to design my own 5x7 font, I reused a character set I found on a German forum, which came in handy on another project I have been working on but haven't posted about yet.

The main board of the calculator is pretty simple. It just holds the microcontroller, CR2032 battery, and some pins for programming. All the wires are 30 gauge wire wrap I got from Mouser, which I really like using. The power lines are thicker gauge, but they are there more for color coding than because I need them to be that thick. 30 gauge copper is supposed to be able to carry more than the few mA I am using without dropping a lot of voltage.

The keypad has 35 keys, which is more than the 25 I was planning on originally. The main reason I did this is because it looked strange to have a square keypad. Also, there were two leftover pins since Xin and Xout can be reused as GPIO if there is no crystal.

 Each key takes up one 3x3 block on the protoboard, which is smaller than the 4x3 spacing of the keypad on my Pocket Calculator project. It turns out, it's not too difficult to bend the legs under the button a little to make them fit the tighter spacing. The LCD and the keypad both plug into the main board with headers.

Since the calculator runs on a battery, it's important to keep the calculator in low power mode as much as possible. This turned out to be surprisingly painless in assembly! Setting up interrupts is very straightforward too. The calculator scans the keypad a few dozen times a second and goes back to sleep if there is no work to be done. Each key has a byte of memory allocated to it to implement a counter for debouncing the keys and showing which keys have been read. My very cheap multimeter shows that the calculator uses a lot less current than the datasheet for the MSP430 and LCD suggest. Hopefully I can borrow better equipment and get a more accurate reading to try to better estimate how long the calculator should run before it needs a new battery.

The interface code is already mostly done and will be the topic of the next post on this project. After that, the only step left is adding the key labels.

Sunday, February 3, 2019

Tiny Calculator: Improved CORDIC


Since my last post I have made a lot of changes to the CORDIC routines I was working on. As you can see in the chart above, the new version fits in less than the 4.1k of the last version even after adding in logarithms. The change came after I found an article about how the HP-35 did CORDIC calculations. Unlike the other descriptions of the method I have used, this version uses an atan table of powers of 10 instead of powers of 2. This lets you shift the arguments by whole decimal places, which is much faster with BCD numbers than powers of 2 . Before, I had wondered if this would be more efficient, but I don't understand the math behind it well enough to modify the routine myself. My implementation of the method the HP-35 uses only takes 90k cycles, compared to the 1.18 million of the last version. The X and Y that the calculation produces, however, cannot be scaled to produce sine and cosine directly. The scale factor depends on the number of rotations, which is easy to precalculate when the angle is halved every iteration, but not possible to know in advance when you use powers of 10 since each iteration requires up to 9 calculations with each affecting the scale factor. As a result, the ratio of X and Y provides the tangent and the HP-35 used identities involving multiplication, division, and square root to generate sine and cosine from tangent. In addition to the 90k cycles for the CORDIC calculation, I would need at least another 140k cycles for these identities. This is 5 times faster than how I was doing it before, although I'm afraid the accuracy would suffer from the added calculations.

The next thing I tried was posting on the HP museum forum, where Thomas Klemm showed me how to do CORDIC calculations in base 10 without resorting to identities. This was a huge help and a much better way to do things than anything I have tried before. The newest routine I have calculates tangent in only 186k cycles and provides sine and cosine without additional calculations! Like in Thomas' version, I tried to make this CORDIC routine more generic so that I can reuse it for inverse trig functions too. Logarithms and powers of e turned out to be much simpler than trig functions using the method described on the same page about the HP-35.

There are still a lot of things to learn about MSP430 assembly. One thing that tripped me up was thinking that RRA automatically shifts a 0 in from the left when rotating when it actually reproduces the leftmost bit instead. Another surprise was that shifting packed BCD by two decimal places is just as fast loading a word from memory, swapping and combining bytes, then writing the result back to memory as it is to just copy bytes directly. I thought the byte copies would be faster, but I was actually able to shave one cycle off by loading and writing words. I rewrote this short section of code five different times trying to save a cycle or two and eventually realized that this is not a useful way to spend my time. This improvement is too tiny to ever be noticeable, and I want to finish this project soon. There are a few other small improvements I have not spent time on since they would provide only a negligible speed up.

The next step is to start working on hardware and the interface code.

Sunday, December 30, 2018

Tiny Calculator: Sine, Cosine, and Tangent

For the trig functions, I started building the same angle table that I used for the CORDIC routines in my RPN Scientific Calculator. Comparing my table to an example calculation I found of how CORDIC works, I noticed that the values are all pi times bigger than the ones in the example. Could I have made the same mistake in my RPN Scientific Calculator? When I get back home from the holidays, I should check to make sure that this does not throw off some of the calculations. Another thing I found out from the same page was that the K value to multiply by after the CORDIC calculation is calculated for a particular number of iterations. In my RPN Scientific Calculator, I included a K value for the maximum number of iterations and truncated it when less precision was used. On second thought, I should have done some testing to make sure truncating the K value to the precision of the argument always yields the best results for a particular level of precision. At the moment I don't plan to redo anything on my older calculators unless something is majorly wrong. It is good, though, to recognize this type of mistake, so I can look out for it in future projects that use CORDIC.

To generate the angle table I used the bc command line calculator. It has a very simple programming language that can run from a script. Interestingly, bc does not seem to do any type of rounding, so the tables I have are unrounded. Maybe I will experiment with a rounded table to see how much of an effect it has. For some of the other tables (including a couple I ended up not needing) I used Python, which has been really helpful. The table itself contains angles descending in size, so I only sto

The first step to implementing the trig functions was replicating the CORDIC calculations in a spreadsheet. This works for about 30 iterations until the numbers become too small for the spreadsheet to handle. Rather than doing bit shift operations like I would on the microcontroller, I multiplied by inverse powers of two, which accomplishes the same goal. When I had that working, I tried generating those multipliers on the MSP430 and multiplying, rather than bit shifts. I thought this might be fairly fast since the multiplier could be left in binary, which makes it quicker to use with the Russian Peasant algorithm, and the amount of zeroes in the multiplier would mean relatively few multiplies altogether. Consider this shortened table of successive inverse powers of two:

Friday, December 14, 2018

Tiny Calculator: Four Functions

The last few weeks I have gone down a little bit of a rabbit hole writing BCD math routines for my Tiny Calculator project. The goal has been to compare different calculation strategies to find which ones are fast but still small enough to fit in the 16k of flash the MSP430 I am using has. Like the addition routines I wrote about in my last post, all of these routines were a lot smaller than I expected. There were also some other surprises about what worked best.

Subtraction
To start with, I based this routine on the setup code for the addition routine, which saves some space. Originally my plan was to make everything modular so that I could substitute pieces of code in depending on what size and speed trade off I wanted, which is why I have separate body and ending options in the table for my addition routine. However, to save space and build one routine off the parts of another, it makes more sense to decide which version to use at the beginning. The only big difference between the two subtraction routines I tried was rolling and unrolling the main loop, with the unrolled version being about 75% faster. It's also about 25% larger but that is only around 50 bytes.

Multiplication
In addition to the straightforward method of repeated additions, I tried the quarter squares and Russian peasant algorithms I learned about doing 6502 BCD multiplication. It was a surprise that using quarter squares was over 10% slower on the MSP430 than the Russian peasant algorithm, whereas it was over 4 times faster on the 6502! Part of the difference may be the speed up I get on the MSP430 by converting each digit of one argument to binary (so it can be halved) only once and saving it, rather than converting it every time like on the 6502. Another major difference is how much slower accessing tables on the MSP430 is compared to register operations. It's interesting how the timing of the architecture can decide which algorithm works the fastest. It's also great that the Russian peasant algorithm doesn't need any tables and is therefore much smaller.

Sunday, November 4, 2018

New project: Tiny Calculator

My Pocket Calculator project has been on the back burner for a few months while I finish my master's thesis. In the mean time, I got interested in doing a much simpler project to make a very small calculator that will hopefully be about 2.5 inches long. This is the size of a 5x5 keypad and the small 128x32 LCD I want to use. Like my first first calculator, it will use a through hole MSP430. The first calculator needed two MSP430s to contain all the firmware, but I think I can fit everything on one chip for this project. It should also be possible to do what I want with the 512 bytes of internal RAM the chip has, so I won't need any external SRAM, and with 25 keys, I also won't need external shift registers. Other than the microcontroller and some capacitors, the only other thing on the board will be a CR2032 battery. The MSP430 needs 2.7v to run at 16MHz, so I plan to run at 8MHz in order to use the battery down to 2.4v. It might be possible to monitor the battery and run at 16MHz as long as the voltage is high enough, but I don't think I will need the extra speed like I did on the last calculator.

One of the main things that got me interested in this project was finding out that the MSP430 has a decimal add instruction that works on packed BCD words. This is really convenient and should be many times faster than doing BCD manually in C like I did for my first calculator. One possibility would be mixing C and assembly to take advantage of features like this, but I am going to try to do the whole thing in assembly to make it as small and fast as possible. Another speed up should come from switching to a 16 byte floating point format. This will let me calculate logarithms and trig functions to the same precision as my first calculator but fit everything in the 512 bytes of internal RAM. Eliminating the bottleneck of transferring data over SPI one bit at a time will probably be the main speed up. For multiplication, I want to try some of the algorithms I tested for the 6502, and for division, I will try out some based on Netwon's Method. For logarithms and trig functions, I'll probably use CORDIC routines again, but I want to see if Taylor polynomials will be much smaller, even if they are slower. With 25 keys, I can fit in just about everything from my first calculator. It should be able to do a little more than an HP-35. The main drawback compared to my first calculator will be less precision with large numbers and less stack space, although neither should be a problem, since there won't be a programmable mode. Also, I plan to keep track of exponents by the byte, rather than the nibble like a did on the first calculator. This will mean losing precision by a factor of 10 in some cases, but it will make aligning numbers during calculation much simpler.

Sunday, December 3, 2017

New project: Pocket Calculator

Recently I got interested in building a very small calculator I can carry around with me. The other calculator projects I worked on are neat, but I don't carry them around because they are too big and fragile. This time I want to make something really practical but also small enough to fit in my pocket. The smallest way I know how to do this with the chips I'm familiar with is using the same LPC1114 in DIP28 package I used for my Programmable RPN Calculator. There are a few changes I would like to make for this calculator, though. First, I want to be able to manipulate all kinds of data on the calculator's stack, such as strings, instead of just floating point BCD numbers. Second, I plan to redo the BCD format I used in the other calculators to store the least significant digits first, which should make them a little easier to deal with. Third, I plan to make all items on the stack variable length, rather than fixed length like on my other calculators. This will be necessary for this calculator since I plan to store the whole stack in the 4k RAM the microcontroller has, instead of on an external SPI RAM chip.

The main new feature I want this calculator to have is a BASIC interpreter. My experience with the first RPN calculator I worked on showed how much of the microcontroller's flash can be eaten up by interface code, so I really don't think I could fit all the calculator functions and interpreter in the LPC1114's 32k of flash. Instead, I plan to store a virtual machine on the chip that can interpret code stored on a large capacity flash or FRAM chip. Retrieving the code over SPI and interpreting it will be much slower than executing code natively on the chip, but I think it will be fast enough for the UI, BASIC editor, and maybe even the tokenizing part of the BASIC editor. On one hand I could switch to a chip with bigger flash, which I am not anxious to do, but I will need some kind of virtual machine anyway to interpret the code generated by the BASIC editor, so it is no loss to use the same virtual machine for the UI. The BASIC programs and editor data will be stored on an SPI SRAM chip, which should work fast enough to edit and tokenize programs, while all the stack and program variables will be stored on the microcontroller.

Tuesday, November 21, 2017

BCD Addition Speed Test: 6502 vs 8051

12345.6789 + 9999.99999 packed BCD on 8051
A few years ago I decided to revisit the microcontroller comparison I had done to see how much of a speed up I could get recoding my BCD addition routine in 8051 assembly. At the time I was surprised that it was 3-4 times faster than the C version. That original BCD routine, which I used for my RPN Scientific Calculator, uses unpacked BCD characters arranged with the most significant bytes first. For the calculator I want to build with a 6502, I wrote a new routine that stores the least significant bytes first in packed BCD. This takes advantage of the 6502's decimal mode to quickly add packed BCD bytes and avoids having to shift all the bytes when an extra byte has to be added for the final carry. It turns out that the 8051 has an instruction, DA, to correct the result of BCD additions from their binary result back into BCD, so it is easy to do packed BCD for it as well. To compare the speed of the two chips for use in a calculator, I translated the 6502 packed BCD routine to 8051 assembly and ran both versions in their respective simulators.

Wednesday, November 15, 2017

6502 BCD Multiplication

In preparation for the 6502-based calculator I am planning on building, I started thinking about the best way to do BCD multiplication. One of the reasons I was interested in working with the 6502 is its built in BCD mode. This works great for add and subtract but the chip does not have any sort of multiply or divide, BCD or otherwise. (Some of the 6800 family I was researching before do have hardware multiply, as does the 8051.) There are several routines that can make BCD multiplication faster, so I tried some of them on the 6502 to see which one works best.

To test these I used the Kowalski 6502 Simulator, which is neat because you can assemble in the simulator and then single step or run the program and see which line is being executed. Another convenient thing is that an input/output window is mapped into memory starting at at $E000. I also like the help window which automatically gives you information on op codes when you type them. On the other hand, the included macro system is extremely primitive and you can't do much with it, especially compared to the excellent macro system in CA65. It has a lot of other shortcomings and is fairly buggy, but I don't want to complain since it is free software. After I got frustrated at the lack of basic macro functionality, I tried assembling with CA65 and loading the binary into the simulator. The diassembler seems to work well but of course there is no way for the simulator to know label or function names. For these multiplication tests I decided to just make do with the simulator since I don't need much macro functionality. In the future, though, I will go back to using the 6502 trainer I made before.

To run the tests I made a loop that multiplies all combinations of BCD numbers $00 x $00 to $99 x $99. The Kowalski simulator has a function to count cycles, so I used that to find the time of an empty loop. For each test I recorded the cycles it took, subtracted the loop overhead time, and divided by 10,000 to get average cycles per calculation. After I was done, I went back and used look up tables for operations like shifting by 4 and halving numbers to speed things up a little. I also tried checking for 0 and 1 as arguments to skip the rest of the calculation, but this was not faster. In the table below, the table size column takes into account all the space the tables take up, including unused padding bytes inside the table. Here are the results in the order I did the tests:

MethodCycle averageCode sizeTable size
1Repeated additions1,596.23340
2Repeated additions, minimize loops1,236.66480
3Shift/add284.80670
44x8 lookup table101.006510k
54x8 lookup table, byte aligned97.006114.8k
6Russian peasant algorithm267.79660
7Quarter square table (half table)115.3385816
8Quarter square table (full table)118.00781,632
9Quarter square table (BCD to bin to BCD)86.00511,816
10Quarter square table (BCD to bin only)60.0034792
11Half squares113.60126200
12Simulated ROM lookup31.002046k

Descriptions of methods below:

Sunday, July 12, 2015

New Project: Programmable RPN Calculator

One of the projects I started on for my Summer Hackathon is a new version of my RPN calculator. This version uses an LPC1114 instead of the two MSP430s the last version used. Hopefully this version will be much smaller and faster. Even though I'm not yet at a good stopping place I wanted to make a post about it so that the last post is not overly long.

Porting the code from the MSP430 was not too difficult. The only real trouble was moving some of the memory registers from the external RAM to the internal RAM of the LPC1114. This really increases calculation speed since it eliminates the bottleneck of accessing external memory. On the MSP430 version I used a preprocessor function to identify and replace any array access to the external RAM with functions calls. This worked well since all of the registers were stored externally but caused a few headaches on the new version since internally stored registers need to be handled differently. One idea I had was to use 32 bit pointers, which wouldn't cause the performance hit they do on a 16-bit system, to somehow encode not only the memory address, but also the memory bank and whether an address is stored externally or internally. It also seems like it would make more sense to allocate memory buffers on a stack as they are needed, rather than hardcoding them in memory. This got me thinking about how other systems handle this problem and I decided to add a way to do that to my 6502 project with a CPLD.

Along the way I also noticed a few areas where I could improve my code. For some reason I got in the habit of reusing generic counter variables like x or i in an effort to save memory. This just makes everything harder to read and does not save any memory since GCC optimizes how variables are used anyway. BCD numbers should also be stored with the smallest places first since that way extending the number by a decimal place only involves incrementing the length field rather than moving every byte of the number one space. In retrospect 255 decimal places is probably way too much for such a simple calculator. This didn't make much difference when I had lots of external RAM but is inconvenient now that I am trying to fit as many registers as I can into the LPC1114's memory.

To read and write the external RAM I'm using the chip's SPI peripheral. It turned out to be somewhat difficult to configure since several of the steps to get it to work have to be done in a certain order. Debugging this was a lot easier with a logic analyzer. After I had it working and got the memory registers straightened out, I was a little surprised to see that calculating sine was slower than on the MSP430. This was a shock since it was so much faster in my microcontroller comparison. I tried raising the SPI peripheral speed to 24MHz, even though the max speed of the RAM is 20MHz, but it was still slower. My next step is to try and measure the clock speed of the SPI with the logic analyzer to make sure it really is going that fast. After I got sine to work, I uncommented other parts of the program in parts to see how much would fit in the flash. Compiling with GCC's -O3 option for speed optimization quickly overflowed the flash but all of it fit in less than 20KB with -Os. One of my gripes with GCC is that it doesn't tell you by how much the firmware is too large, so you have no clue how much you would need to shave off for it to fit.

Initializing and toggling the pins of the LPC1114 is a bit more complicated than on the MSP430 since different pins have different configuration bits and the pins themselves are not mapped into memory in order. I had a look at the HAL library and it seems to use quite a bit of code for what I want to accomplish so I wrote a simple class for handling pins. Luckily I can use C++ since I am just compiling with GCC, unlike with OpenSTM32 where I was stuck with plain C. One neat thing someone showed me was how to use operator overloading so that something like "Pin=1;" does the same as "Pin.high();"

Since I have so much space left over in the flash, I started adding a keystroke programming function. This was one of the neat things I have always liked about earlier calculators. I am nearly done with the editor on the screen for it, which I'm working on with the PC version of the program since it is much faster to test. The next time I do a project like this I will put the PC and embedded version in the same file and enable them with include statements instead of copying the changed sections of the PC version. So far I am only adding the ability to repeat keys and not loop or branch since I want to finish this and at least one other project in time for Makevention in August. When I have more time I hope to add that functionality.

Sunday, December 28, 2014

Microcontroller Showdown, Revisited

Back in March I finished the microcontroller comparison of a few chips I was considering using. The 8051 based chips all fared poorly in BCD calculations, which is the main thing they would be used for in another calculator project. Some other 8051 fans pointed out that tests like mine test the compiler more than the chip and the SDCC compiler does a lot less optimizing than GCC. So, I decided to recode the BCD Add routine from the test in assembly. At the beginning I didn't consider this because I thought I would only ever write C for the 8051, but after writing assembly for the 6502, I was excited to try it for the 8051 too.

For this test I used the MCU 8051 IDE simulator. It is really impressive! Being able to see all the RAM and registers helped a lot. It is similar in some ways to what I hoped to accomplish with my 6502 Virtual Trainer. When I translated the original BCD Add function from C, I left out the parts used for subtraction, since they weren't used in the test. Also, some of the values that don't change inside loops are calculated once before the loop and stored for use later. This makes sense because a good C compiler would do this for you. All values are stored in the internal DATA, although this would be far too small for real calculations. The simulator can also work with SDCC, so I was able to simulate the function in C after commenting out the parts for subtraction.

The assembly took a simulated 440us to execute. The C version took between 1365 and 1732us depending on memory model and whether the BCD data was stored in DATA or XDATA. Curiously, storing it in XDATA was always faster. The medium memory model was faster than the large memory model. It seems then that hand-coding the routine in assembly is 3-4 times faster. To be fair, the routines for other architectures might also show a speed up if they were rewritten. Compared to the original numbers of the test, a 3x speedup would make the DS89C450 faster than the MSP430 for this routine. The difference might actually be a little bigger since this test used an upgraded version of SDCC that might optimize better. With that in mind, an 8051-based calculator with external bus (coded in assembly) would outperform an MSP430 with SPI SRAM. That is a bit of a surprise after the results of the first test.

The LPC1114 could also be sped up a little. In the original test the chip was configured to run at 50MHz. Because the flash runs at a maximum 20MHz, 3 wait states are required when executing from flash. However, 3 wait states is a little wasteful since 2.5 would be enough. Running the chip at 40MHz would only require 2 wait states, and would let the flash run at full speed. I'm not sure this would give a whole 16% speedup but I imagine it would offer a little bit of a boost.

Monday, July 29, 2013

RPN Scientific Calculator: More CORDIC Routines

After finishing the CORDIC routine for logarithms I started on the CORDIC routine for trig functions. For this I needed a different look up table and a different function, but it didn't take up much room in the flash. The table for pre-computed logarithms is stored compactly in flash and the same routine that unpacks it into the external memory is also used to unpack the trig table. With this I can calculate sine, cosine, tangent, and arctangent. It should also be possible to calculate arcsine as well but I haven't tried yet.

To test these new function I tried calculating atan(tan(37)). When using 16 decimal places for the calculations this gives the answer 36.9999999999999781, which is pretty accurate. Unfortunately, this took over two seconds, which is just too slow. The logarithm and powers of e functions were at least twice as fast. In order to speed things up I tried to eliminate as many reads and writes to the external memory as I could. One thing I didn't notice when I wrote the original functions is that the loop condition for a for loop is recalculated each iteration. When the condition depends on a variable in external memory, the variable is fetched on every iteration, which is wasteful if the variable hasn't changed. After changing the code to use local copies of external variables whenever possible, I was able to cut down external memory access by almost 25%.

25% wasn't quite enough so I looked at the code I was using to right shift. This allows me to divide numbers by 2 quickly but takes some extra coding since shifting in BCD is a little more complicated than a normal binary shift. Because of the extra work involved in keeping everything straight during BCD shifting, I was doing shifts one bit at a time. This means a 58 bit shift, for example, would simply do 58 shifts of 1 bit each. As you can imagine this is not efficient and was a big part of the slow down in the code. My solution was to use as many 4-bit shifts as needed, then a few 1 bit shifts at the end to finish it off.

Shifting by 4 bits in BCD is fairly easy. As you probably know, shifting by 4 bits is the same as dividing by 16, and dividing by a number (16 in this case) is the same as summing the results of dividing each decimal place by that number. Since there are only 10 possibilities (0-9) for each decimal place, I stored the results of dividing each possibility by 16 in a look up table and used that to sum the results. Here is an example:

789 ÷ 16 = 700/16 =   4375
                  80/16 =     5000
             +     9/16 =      5625
                               49.3125

The values 4375, 5000, 5625, etc are stored in the look up table. The sum of these results are stored in local RAM since 6 bytes is enough to keep track of the summing long enough to deal with any carries before finally writing the last byte to the external RAM. Doing it like this I only need to read and write every decimal place once per 4-bit shift. This cuts down the number of external memory accesses down to almost one third of what it was at the beginning and allowed me to calculate atan(tan(37)) in a little over a second. All of this fits in 8.1K of Flash meaning I just broke the halfway mark of what the MSP430G2553 chip I am using can hold. If there is any space left over at the end, I would like to implement a similar 8-bit shift routine as well to speed things up even more.

Wednesday, June 12, 2013

RPN Scientific Calculator: Software Update

Work continues on my calculator. Each byte of a BCD number now holds only one digit instead of two. This eliminates the functions that were needed to align and pad numbers when every byte held two numbers. It also makes calculations a little simpler and reduces the amount of space the functions take up in the Flash.

Another improvement is that arrays can be stored in the external SRAM and accessed similarly to how internal memory is accessed. To read or write anything to the external memory a function has to be used. That means a simple equation like this:
X+=Y*Z-Q;
would become this if those variables were stored externally:
 RAM_Write(X,RAM_Read(X)+(RAM_Read(Y)*RAM_Read(Z)-RAM_Read(Q));
This is difficult to decipher and inconvenient to use when writing code. My solution was to make a small program that preprocesses the source code and replaces any variables that should be stored externally with their corresponding read and write commands. These variables are marked off with #pragma directives. #pragma is a note to the compiler to do something special that may be specific to that compiler. If the compiler doesn't recognize the directive, it is ignored. Here is an example of what the preprocessor would do.

This is unprocessed code:
void puts(unsigned char *msg)
{
     #pragma MM_VAR msg
     for (int i=0;msg[i];i++) putchar(msg[i]);
}

int
main()
   
     #pragma MM_OFFSET 200
     #pragma MM_DECLARE

     unsigned char text1[30];
     unsigned char text2[30];
     #pragma MM_END

     text1[0]='A';
     text1[1]=0;
     puts(text1);
}
 This is preprocessed code:
void puts(unsigned char *msg)
{
     #pragma MM_VAR msg
     for (int i=0;
RAM_Read(msg+i);i++) putchar(RAM_Read(msg+i));

}

int
main()
   
     #pragma MM_OFFSET 200
     #pragma MM_DECLARE

     unsigned char *text1=(unsigned char*)200;
     unsigned char *text2=(unsigned char*)230;

     #pragma MM_END

     RAM_Write(text1+0,'A');
     RAM_Write(text1+1,0);

     puts(text1);

}
Arrays are converted to pointers that store offsets to the external memory. This way none of the function prototypes have to be changed. The code should work the same way whether the variables are stored in internal or external RAM. External memory can be turned off if needed to make tracking down bugs easier. One disadvantage to this is that function arguments must be either internally or externally stored but a function can't accept both types for one argument. For things that need both I will need a wrapper function. The preprocessor doesn't support all of the C standard since I only spent about a day on it. Adding support for all of the possible ways there are to access a variable would take a lot more work and I wouldn't be likely to use that functionality anyway. Things like variable names that span multiple lines or variable assignments inside of other statements aren't supported but I didn't end up using any of those features in my code.

The new code for adding and subtracting BCD numbers fits in about 2K, including LCD driving code. Using the preprocessor to store all the values externally adds another 500 bytes. The code for multiplication is also much smaller than the last version.

Saturday, May 18, 2013

RPN Scientific Calculator: Multiplication

The next step of the software for my calculator is multiplication. In Binary Coded Decimal (BCD) this is fairly straightforward. Every decimal place of the first number has to be multiplied by every decimal place of the second number. The tricky part is keeping the results lined up and then putting the decimal point in the right place at the end. Here is an example running on the MSP430:


One advantage of BCD is that it avoids the rounding errors that occur in floating point calculations. This quickly becomes apparent when you start multiplying decimal numbers. Even in this example using fairly small numbers there is a rounding error:
Floating Point:
835.2533 x 907.042 = 757609.823739

Binary Coded Decimal
835.2533 x 907.042 = 757609.8237386
For most uses floating point offers enough precision but a scientific calculator should be as accurate as possible, so BCD is a better choice.

While working on this I was able to find a bug in my code for addition and fix it. I also added a function to shift numbers one decimal place so they will be aligned properly for multiplication. This routine is sometimes necessary since each byte holds two decimal numbers. Routines like this take up space in Flash, which is limited to 16K on value-line MSP430s. One way to avoid having to shift numbers is to let each byte represent one number instead of two. Although this would use twice as much RAM, it would simplify programming and use less space in Flash. This is what I will do if I run out of room for the firmware. Right now I plan to use 128K parallel SRAM chips from Alliance, so running out of RAM wouldn't be a problem. (Of course 8k of SRAM would have been enough but I don't have any of those with me.) Another option would be to write all or part of the BCD routines in assembly. This would help a lot since the MSP430 has an op-code to add BCD numbers. It also handles carries natively which is more efficient than storing it in a variable and checking it explicitly like my code does now. Currently, the program is only 3.3K including the part that handles the LCD. How much I can fit in the remaining Flash will determine what changes I make.

Monday, April 8, 2013

New Project: RPN Scientific Calculator

My interest in electronics started because I would like to build calculators like the ones I used to collect. Now I plan to build a scientific RPN calculator. A three inch graphical LCD would work well for this but most cell phone screens I can easily find are a little bit too small. For the time being I will continue using the 16x2 LCD I found.

For this project I intend to use an MSP430. The challenge of this will be that the MSP430G2553s I have only have 512 bytes of RAM. To begin with I decided to start on the programming since this will probably be much more work than the hardware. Although I want this calculator to use RPN, it would also be good if it could evaluate algebraically as well like the HP-49G. It will hopefully also be useful to have a small parser that works on a microcontroller for some other projects I want to do. Here is the parser running on my LaunchPad and evaluating the equation 13*(4+25*13)/((67-33)*2^3):


 
At first I wanted to use recursion because this can really simplify parsing but that's not really an option since it would use a lot of stack space. Instead, it evaluates any expressions it can and stores the result in memory then writes a pointer to that memory in the place where the expression was. Doing it like this instead of tokenizing the whole string before evaluating saves memory. The results of operations are stored starting at the end of the string that holds the expression so that as the expression is evaluated and becomes smaller, memory is freed which can be used to store more results. So far this parser fits in about 2k of Flash.

The second part I worked on is a Binary Coded Decimal format. This will be more accurate than floating point since it will be able to store any number that will fit in available memory. Each byte of data contains two numbers from 0 to 9. Now numbers are limited to 512 digits in length but this can easily be increased, although it probably wouldn't be useful on such a small screen. I have code for adding and subtracting, so multiplication and division should be easy to implement using these. I was able to fit this into less than 2k of  Flash so with the parser I should still have about 12k of flash for other functions. Here is an example using numbers small enough to fit on the screen: