v0.1 board believed to be reading Vbat, Pressure, and X/Y/Z correctly now,
[fw/openalt] / README
1   J.C. Wren
2   2007/07/22
3   jcwren@jcwren.com
4
5   The most recent version of this package may be found at http://jcwren.com/arm
6
7   I'm changing the format of how updates are documented.  Rather than including
8   it in the body of the text, they will be appended to the front, with a date.  
9
10   2007/07/22, version 1.20:
11
12     Added interrupt driven I2C master transmit and receive code.  I'm pretty
13     confident that all the cases are handled correctly, but I don't have any
14     way to introduce certain errors for testing.  There are now two files in
15     the ./i2c directory, "i2cInt.c" and "i2cPolled.c".  Edit the ./i2c/Makefile
16     to select interrupt drive or polled I2C handling.  There is some support
17     for debugging I2C the interrupt drive routines.  As interrupts occur, the
18     various state changes are recorded, and the 'i2c dump' command will display
19     them.  This is disabled by default, but can be enabled by editing the
20     ./i2c/i2cInt.c file and defining I2C_DEBUG.
21
22     Added raw I2C support.  The 'i2c' commands allow directly reading and
23     writing an I2C device (as opposed to using the LM75 wrapper for LM75's, or
24     the EEPROM wrapper for EEPROMs).  See 'i2c help' for a list of commands.
25     Note that when reading from an I2C device via the raw commands, a maximum
26     of 16 bytes may be read or written.  If you need more, change the buffer
27     sizes in the appropriate commands in ./monitor/monitor.c, and also the
28     maximum number of arguments in the command dispatch table (commandListI2C).
29
30     Added EEPROM support.  The 'ee' subset of commands allow reading and
31     writing of a 24Cxxx series type EEPROM.  The code is currently targeted at
32     an Atmel 24C1024 128x8 part (I had some laying around).  It should be
33     pretty easy to rework them for any smaller part.  See 'ee help' for a list
34     of supported commands.
35
36     Fixed the LM75 support to allow writing the config, TOS and THYST
37     registers.  The previous versions allowed reading the registers, but I
38     forgot to write code to allow changing them.  Oops.
39
40     Moved 'date' and 'setdate' commands into the 'rtc' sub-menu as 'get' and
41     'set', respectively.  Added 'alarm' command that allows setting an alarm
42     date/time, or disabling it.  When an alarm fires, 'ALARM -- YYYY/MM/DD
43     HH:MM:SS' is printed to the console.  Also added 'periodic', which when
44     enabled, prints 'PERIODIC -- YYYY/MM/DD HH:MM:SS' to the console at the top
45     of every minute.  The RTC also demonstrates using the default vector
46     address functionality of the non-vectored IRQs in the VIC (alternatively,
47     by un-defining RTC_NONVECTOREDIRQ in the ./rtc/rtc.h file, a regular
48     vectored IRQ can be used).
49
50     Note on the RTC alarm and periodic output: It's really gross.  Console
51     input is handled by a libc read() call.  This is a blocking call,
52     implemented by doing a FreeRTOS xQueueReceive in the console device code
53     (UART 0, UART 1, or USB).  So the only way to get the read() to return so
54     the CCI can output the message is to reserve the special characters 0xfe
55     and 0xff (something a user can usually never type).  When the CCI getline
56     routine sees either of those characters, it immediately returns.  These
57     characters are then checked for by the CCI command parser, and either an
58     alarm or periodic message output.  If the user is in the process of typing
59     in a command, the input will be lost.  Without totally rewriting the CCI
60     into a queue based message passing architecture, I couldn't find a more
61     elegant way to handle this.  So basically, the RTC interrupt sends a 0xfe
62     or 0xff into the input buffer for the console device, which then returns
63     the character, which is then processed by the CCI code.
64
65     Changed the 'task' command to a 'mem' sub-command.  Added the 'map'
66     command, which shows how memory is allocated.  Overview: The .txt section
67     contains the program code, the initialization values for static data in RAM
68     (statements like 'static int i = 172;'), and the glue section (I believe
69     this is where ARM/THUMB inter-networking code is placed).  The .data section 
70     is the area of RAM that gets initialized from the constants in FLASH at 
71     startup (so that i == 172).  The .bss section is all static data that is 
72     zero length (statements like 'static int foo [12]').  The 'map' command 
73     prints out the starting and ending address of each area (size calulation is 
74     left to the user).  Also included is the starting and ending addresses for 
75     the various stacks (undefined, abort, FIQ, IRQ, service), the start of heap,
76     and the current heap end.  The scheduler executes in supervisor mode, tasks 
77     execute in system mode.
78
79     Added FIQ demo.  Timer 1 is set up to interrupt at 8hz (8 times a second,
80     or every 125 milliseconds), and is configured as a fast interrupt.  The
81     interrupt handler does nothing more than increment a counter.  The 'fiq on'
82     command will enable the timer, 'fiq off' will disable it, 'fiq count' will
83     print the counter value, and 'fiq clear' will reset the counter to 0.  As
84     long as the FIQ is enabled, it should be merrily counting along.  NOTE: the
85     actual FIQ vector is in ./boot.s.  Also in this file is the FIQ stack size.
86     I've set it to 32 bytes (8 words).  This was derived empirically by
87     examining the lpc2148.lst file, and seeing how many registers were pushed
88     by the fiqISR code.  Only 3 registers are pushed, so 8 words was deemed
89     enough space.  An interrupt that actually does anything substantial will
90     require more stack space, and the FIQ_STACK_SIZE should be adjusted
91     accordingly.  The FIQ in the CPSR is enabled by FreeRTOS when it starts the
92     scheduler, just like the IRQ.
93
94     The stacks have been tuned down pretty small to allow a larger heap area.
95     Many boot.s files allocate 1K for the supervisor stack, and another 1K for
96     the IRQ stack.  I've tried to exercise all the functions in the demo to get
97     a feel for stack usage, and both of those stacks have been tuned down to
98     256 bytes each.  There shouldn't be any issue with using a lot of stack in
99     any code prior to the call to vTaskStartScheduler(), since the supervisor
100     stack will overflow into system/user stack space.  Once tasks are running,
101     they have their own private stack spaces inside the FreeRTOS allocated
102     memory.  If the interrupt routines are modified to use more dynamic space,
103     then the interrupt stack may need to be increased.  So far, I've seen less
104     than 50% utilization.  The FIQ stack is very small, as it does nothing more
105     than increment a counter.  More complex FIQ routines will need more space.
106
107     Fixed problem with CCI 'mv' command failing.  Default compiliation options
108     for newlib for ARM don't define HAVE_RENAME, so the newlib rename() was
109     trying to do the link/unlink method of rename a file.  FatFS (and FAT file
110     systems) don't support links, so this was always failing, since link()
111     returns -1.  Provided our own rename() in newlib/syscalls.c to override the
112     newlib rename().
113
114     Added a data abort, prefetch abort and undefined instruction handler.   The
115     abort handler works by saving the state of the CPU to a block of memory,
116     then enabling the watchdog to force a reset.  This method was used instead
117     of printing directly to the serial port, as some people are using the USB
118     as the console port, and there's no gaurantee that the system is still
119     stable enough for USB to work.  So instead, the state is saved, the reset
120     is forced, and the user can then use the 'abort' set of commands to examine
121     the system state.  The 'regs' command will display the registers at the
122     time of the abort, and print the opcode of the instruction that failed
123     (except for prefetch abort).  The 'clear' command sets the memory used by
124     the abort handler to 0's.  The 'dirty' command sets the sigil used to
125     indicate if the abort memory contains valid data.  'dabort', 'pabort' and
126     'undef' force each of the types of aborts.  To try it, start the system,
127     type 'abort clear', then 'abort regs'.  All registers should be 0.  Now
128     type 'abort dabort'.  This forces an access to location 0x40008000, which
129     does not exist.  After the LPC2148 has reset, type 'abort regs'.  Examine
130     the PC value, open the lpc2148.lst file in an editor, and search for that
131     address.  You should find that the abort occurred in the monitorAbortDabort
132     code, at the 'ldrb' instruction.  Note that if the PC is showing somewhere
133     in the boot.s code area, it's likely a double abort is occuring.  Most
134     likely the stack pointer was already corrupted at the time of the abort,
135     and when the stack is being copied, it's reading from memory that will
136     cause a data abort.  After an abort, you'll want to do a 'wdt clear' to
137     clear the WDMOD.WDTOF flag, otherwise you'll be unable to re-enter ISP mode
138     without a power cycle.
139
140     Added 'misc' menu, which right now consists of the 'sizeof' command.  This
141     displays the size of the common C data types (just in case you weren't sure
142     a void * is 4 byes).  I'll add others here later, like when FreeRTOS starts 
143     exposing structure sizes in a future release.
144
145     Updated FreeRTOS to version 4.4.0
146
147     CURRENTLY BROKE, WAITING FOR JTAG DONGLE (feel free to submit a fix).
148     Added USB mass storage capability.  If CFG_USB_MSC is defined in the
149     Makefile, USB serial support will be disabled, and mass storage enabled.
150     This allows the MMC/SD card to be mounted like a disk drive.  DANGER!  The
151     CCI commands for file management remain enabled.  This means you can create
152     a file on the Windows (or Linux) mounted device, and see the changes from
153     the CCI.  HOWEVER: The SPI routines that read/write the MMC/SD card are not
154     thread-safe, so a USB request to read/write the disk can interrupt a CCI
155     command.  It's crazy dangerous to actually use the CCI file commands while
156     the MMC/SD card is mounted under Windows or Linux.  What you can do is
157     mount the MMC/SD card, copy files to/from it, unmount it, then use the CCI
158     commands to see that things really changed.  A later revision of the demo
159     package will likely at least protect the SPI I/O from being interrupted
160     (although this defeats the 'Real' in RTOS to do so).
161
162
163 Overview:
164
165   This package demonstrates using LPCUSB and FatFS under FreeRTOS on the Olimex
166   LPC2148 board, using GCC and newlib.  Examples include FreeRTOS queues and
167   semaphores, LPC2148 analog to digital converters (ADCs), external interrupts,
168   the real-time clock (RTC), general purpose IO (GPIO), serial ports (UARTs),
169   and USB.   Also included is a newlib syscalls.c that almost completely
170   implements all syscalls.c functions.
171
172   The package (as built, .hex file included) presents the USB port as a virtual
173   comm port.  The virtualized port is used to talk to the console command
174   interpeter (CCI), that allows various functions to be exercised.
175   Alternatively, the package can re-compiled to use UART0 as the console port. 
176
177   If a GPS with NMEA output at 4800 baud is connected to UART1, one of the
178   tasks will parse the NMEA input stream, and display a position report.  In
179   addition, the RTC may be set from the GPS time/date.
180
181   FatFS support is included, and the CCI has several Unix-y commands to
182   manipulate files (mkfs, df, ls, mkdir, rmdir, rm, mv, cp, chmod, and sync).
183   There is also a command that allows through-put testing on the MMC/SD card. 
184
185   This package exists because I wanted to familiarize myself with the LPC2148,
186   FreeRTOS, FatFS and LPCUSB for a personal project, using GCC and newlib (who
187   can afford those commercial packages?  Not I).  By slightly modifying the
188   resulting framework, I was able to produce a package that others may possibly
189   find useful.
190
191
192 Software tools:
193
194   The package compiles using the arm-elf GCC package.  Gentoo users can
195   install this by emerging the 'crossdev' package, then 'crossdev -t arm-elf'.
196   Once the arm-elf verison of GCC is installed, the package can be rebuilt with
197   'make'.    
198
199   To program the board, the Philips LPC2000 Flash Utility v2.2.3 Windows tool
200   was used.  There are Linux based tools for programming the LPC21xx parts, any
201   of which support the LPC2148 should be suitable.  It may be normal, but I
202   couldn't get the board to program at speeds other than 19200 and 38400.
203
204   ProComm was used to talk to the console port on UART0, and HyperTerm to talk
205   to the console port when using USB (Don't get me started on how crappy
206   HyperTerm is.  I *DESPISE* this abortion, and figure that Hilgraeve must have
207   pictures of Gates with a goat or something.  We can argue about MS quality
208   all day long, but HT has all the "quality" of a 6 year olds first programming
209   project in QBASIC.  The only reason it was used was because ProComm can't
210   talk to COM18, which is what the virtual serial port appears as).
211
212   If using the USB virtual comm port under Windows, the 'usbser.sys' and
213   'usbser.inf' files may be needed.  Often, these files are already on the
214   drive somewhere, and Start->Search->Files can be used to located them.  If
215   not present, they are included in the ./Windows directory in the package.
216
217   Under Linux, 'minicom' should be able to talk to both the serial port and the
218   virtual comm port the USB port appears as.  Bertrik's wiki, located at
219   "http://wiki.sikken.nl/index.php?title=LPCUSB", has a note about using LPCUSB
220   under Linux.
221
222   The default baud rate for UART0 is 115200.  The baud rate selected for the
223   USB virtual comm port is irrelevant, and may be any speed.
224
225
226 Rebuilding it:
227
228   Simply typing 'make' should build the entire package.  The FreeRTOS modules
229   will emit several warnings about type punned references, which can (safely?)
230   be ignored.  
231
232   If you wish to use UART0 for the console port, edit ./monitor/monitor.c, jump
233   to near line 938, and change the "#if 1' to '#if 0', then recompile.
234
235   If you wish to change the baud rates for UART0 or UART1, edit ./main.c, jump
236   to near line 62, and change the rates.  Any standard baud rate should produce
237   usable results.
238
239   'make clean' will clean the project, removing the ./*.hex, ./*.lst, ./*.map,
240   ./*.elf files, and ./common/common.a, along with all *.o and .depend files in
241   any sub-directories.
242
243   'make tags' will rebuild the ctags file for 'vi' (and no doubt emacs, if
244   you're one of "them").
245
246
247 Hardware (required and optional):
248
249   Olimex LPC-P2148 board (required)
250   USB cable (optional)
251   Serial cable (optional)
252   GPS with NMEA output and serial cable (optional)
253
254
255 Using it (Windows):
256
257   For the purposes of these instructions, it will be assumed that COM1 is the
258   serial port on the host PC, a USB cable is connected to the LPC-P2148 board
259   and the PC, and that the Philips LPC2000 Flash Utility V2.2.3 will be used
260   for programming.  Please note that Windows 2000 was used, and that dialogs
261   for Windows XP are probably slightly different.  If you're using Vista, I'm
262   surprised it can stay up long enough for you to read this document...
263
264   Connect the RS232_0/ICSP DB-9 on the LPC-P2148 board to the comm port on the
265   PC, using a straight-thru serial cable.  Set both the ICSP slide switches
266   (located near the RS232_0/ICSP DB-9 connector) to the 'on' position (towards
267   the DB-9 connector), then press the reset button (located next to the ICSP
268   switches).  
269
270   Configure the Philips utility for COM1, 38400 baud.  Click the 'Read Device
271   ID' button.  LPC2148 should appear in the 'Device' text field.  Note that the
272   device ID has to be read to set the value, as there's a nasty bug in the
273   utility that prevents selecting it from the drop down list.
274
275   Click the "..." button in the 'Flash Programming' block, then locate and
276   select the 'lpc2148.hex' file, followed by clicking the 'Upload to Flash'
277   button.  At this point, the flash image should start being programmed.
278
279   When it completes, set the two ISCP slide switches to 'off', and press the
280   reset button.  The 'LED1' LED should start flashing.  
281
282   If Windows already does not already have the 'usbser.sys' driver installed, a
283   dialog will appear regarding the discovery of new hardware.  (I don't
284   remember how the dialog goes, so you'll have to infer your way through this
285   process).  When prompted for the driver, navigate to the ./Windows directory,
286   and select 'usbser.inf'.  This should install the driver for the virtual comm
287   port that will support the USB port.
288
289   Right-click on the 'My Computer' icon on the Windows desktop, select
290   Properties, then the Hardware tab, followed by 'Device Manager'.  Click the
291   '+' on the 'Ports (COM & LPT), and there should be an entry for "USB CDC
292   serial port emulation (COMxx)" (where 'xx' will be a number).  Note the COM
293   port for use with HyperTerm (see previous rant).
294   
295   Start HyperTerm (Start->Programs->Accessories->Communications->HyperTerm)
296   (see previous rant).  When the dialog appears, type a name for the connection
297   (The COMxx name is a good choice).  Click the drop-down box under 'Connect
298   using'.  Select the COMxx port name from the drop-down list.  Click 'OK',
299   followed by File->Save.  Now click the third icon from the left, which looks
300   like a telephone with the handset on the hook.
301
302   If all went well, typing 'help<return>' should show a list of commands
303   supported by the CCI.  If so, congratulations!  You can now play with various
304   commands.  If not, there's not much advice that can be offered at this point.
305
306   Baldur Gislason informed me that the Philips Flash Utility has been replaced
307   by by Flash Magic (http://www.flashmagictool.com).  I gave this a try, and it
308   worked well enough.  It's a nicer interface, but it seems a tad slower.
309   Rather than go into detail how to use it, I'll just say that I set the devce
310   to LPC2148, interface to 'None (ISP)', the oscillator frequency to 12.00000,
311   and checked the 'Erase blocks used by Hex File', and it just worked.
312
313
314 Using it (Linux):
315
316   Eeek!  This needs to be written.
317
318   (Richard T. Stofer says that Debian plays nicely with the LPCUSB code.  with
319   the virtualized comm port appearing as ACM0.  'minicom' can talk to this
320   port).
321
322
323 Hardware thingies:
324
325   The two pushy buttons on the LPC-P2148 board (B1 and B2) enable and disable
326   LED2.  Pressing B1 should light LED2, pressing B2 should extinguish it.
327   These buttons are connected to the EINT2 and EINT0 lines, respectively.  The
328   associated code demonstrates handling an external interrupt, and toggling an
329   I/O pin in the interrupt service routine (ISR).
330
331   The potentiometer, AN_TR, is connected to ADC0, channel 3.  The 'sensors'
332   task checks the value every 100 milliseconds.  The software divides the pot
333   into 4 zones, each covering about 1/4 of the range the pot may be rotated.
334   When the pot is fully counter-clockwise, LED1 will be on for 200 milliseconds
335   and off for 800.  When the pot is moved to the 2nd zone, the on/off times
336   become 400ms/600ms.  The 3rd zone has on/off times of 600ms/400ms, and fully
337   clockwise is 800ms on, 200ms off.
338
339   LED1 is controlled by the LED task.  This is a lower priority task.  Each
340   time a single on/off cycle has completed, it's message queue is checked to
341   see if the blink ratio times should be changed due to the AN_TR pot changing
342   zones.
343
344   LED2 is controlled by the B1 and B2 pushy buttons, as mentioned above.
345
346   The DAC output on the AOUT pin changes every 100 milliseconds by 1/64 of the
347   range of the DAC (0.0515625 volts).  The generates a sine wave with a period
348   of 12.8 seconds, or 0.078125 Hertz.  Hang a 'scope or DVM on the AOUT pin to
349   see the change.
350
351   The I2C routines are setup to talk to a LM75 temperature sensor.  These can
352   often be found on old PC motherboards, or as samples from National.  The I2C
353   demo code is a simple polled approach, and does not take advantage of either
354   interrupts or the I2C state machine.  The 'lm75' CCI command allows reading
355   and writing of the configuration, THYST and TOS registers, and reading of the
356   temperature register.  The 'lm75 mode' command determines if the registers
357   are read using an I2C repeated start sequence instead of an I2C stop then I2C
358   start.  Repeated starts are faster, and allow for holding the I2C bus in a
359   multi-master environment.  The default is repeated starts (mode 0).  There is
360   one potential spot for the code to hang.  If the I2C bus fails to release SCL
361   (if the I2C device is powered down, perhaps), it will hang waiting for the
362   status interrupt bit to change.  Any hard while loops should be wrapped in a
363   counter or timer check.
364
365   Demo now includes watchdog timer example.  'wdt test' enables the watchdog.
366   If no command is typed for 10 seconds, the system will reset.  'wdt status'
367   can be used to examine the current watchdog state and the RSIR register
368   (which allows determination of why a reset occurred).  Use 'wdt clear' to
369   clear the RSIR status.
370
371
372 Sort of hardware thingies:
373
374   The SWI demo code is taken from several different projects, and culled down
375   into something I felt was more readable, and better for explanations.  The
376   CCI 'swi' commands allow setting the state of, turning on, turning off and
377   toggling LED2.  The commands starting with 'a' use the assembly interface
378   (assembly sequences are used to affect LED2), whereas the commands starting
379   with 'c' manage LED2 in C.  Note that the pushy-buttons also toggle LED2, so
380   there can be some interaction.
381
382
383 CCI commands:
384
385   If you're a Linux user, most of the file commands are fairly self
386   explanatory.  If you're not a Linux user, you should be, because it's better
387   on our side of the fence.  The file commands require that a MMC/SD card be
388   installed in the MMC/SD slot.  BEFORE USING THE FILE COMMANDS, USE THE
389   'mount' COMMAND TO MOUNT THE MMC/SD CARD.  Note that the first partition on
390   the MMC/SD card will be mounted, and this is the only one supported.  It must
391   be a FAT12, FAT16 or FAT32 partition.
392
393   If the MMC/SD card is not formatted with a FAT12/FAT16/FAT32 file system, you
394   can use the 'mkfs' command to create it.  If anything already exists on the
395   card, 'mkfs' will wipe it out.  
396
397   Note that while a fairly good success rate has been obtained with the cards
398   on hand, one Sandisk 64MB MMC card did not work.  Not sure why, but the MMC
399   drivers are probably not handling something quite right.
400
401   'cpcon <filename>' allows a text file to be created from the CCI.  Enter text
402   until you're bored, then type ctrl-d save and exit.  Note that whatever
403   characters are typed are saved into the file verbatim.  This means that
404   characters like backspace are actually put into the file (feel free to
405   improve that code...)
406
407   Before creating any files, you may wish to set the system date, so that files
408   are date/time stamped properly.  If a GPS with NMEA output is connected to
409   RS232_1, you can use the 'gps' command to verify the serial connection, that
410   NMEA data is being parsed, and that the GPS has acquired (required for the
411   date/time to be set).  If you have no GPS attached, you may enter the date
412   and time as parameters.  'settime 2007/07/08 22:51:25' will set the date and
413   time to July 8th, 10:51pm and 25 seconds.  No timezone info is applied, so
414   date/times acquired from the GPS are UTC.  Date/times set manually may be set
415   to local time or UTC (or something completely random, if you're into that).
416
417   The 'thruput' command allows measuring MMC/SD read and write performance.
418   Eight file sizes are used: 1K, 8K, 16K, 64K, 128K, 512K, 1MB, and 2MB.  A
419   temporary file is created on the MMC/SD card.  Measurements can be done one
420   of four ways:  'noints' (fastest, but disables all tasking), 'normal' (CCI
421   task priority is not changed, no tasks are suspended), 'suspendall' (all
422   tasks are suspended, no context switches made, but 10ms interrupts still
423   runs), and 'high' (CCI task is elevated to highest priority for duration of
424   test).  Oddly, writes are faster than reads when not using the 'noints' mode.
425   I have not yet researched why.  Leaving interrupts enabled *seriously*
426   impacts the file system performance, nominally by a factor of 20.
427
428   Richard T. Stofer noticed that this slow down only appears when using the
429   'usbser.sys' drivers under Windows.  When using the Linux ACM drivers, or
430   when using UART0 as the console port with the USB cable disconnected, this
431   problem does not occur.  We can only assume that the Windows driver sends
432   lots of (needless) packets (yet another reason to switch to Linux!)
433
434   The 'date' command will report the current date/time from the RTC.  If you
435   have an external 3V battery plugged into the BAT connector, the RTC will
436   preserve it's values across power-downs.  Regardless of the battery presence,
437   date/time will be preserved across resets (as long as power is not removed).
438
439   The 'sensors' commands reports very little useful information.  The sensors
440   task executes every 100ms, and samples the ADC connected to the AN_TR
441   potentiometer.  Every time the task runs, the sensors counter is increment by
442   one.  If the AN_TR pot is adjusted far enough to change the zone, the ADC
443   changed value will increment.  See the section above on the pot.  The
444   associated code demonstrates running a high priority task with a constant
445   execution frequency, sampling an ADC, and sending a message to another task.
446
447   The 'mem' command displays the various tasks running, and the amount of
448   unused stack available to each task, along with the task priority and such.
449   The associated code demonstrates the 'vTaskList' RTOS call.  Note that in a
450   'real' system, leaving the task trace code enabled (configUSE_TRACE_FACILITY)
451   imposes a slight penalty on context switches, which may be undesirable.
452   
453   The 'iap' commands allow experimenting with the In-Application Programming
454   (IAP) code.  The demo code demonstrates preparing, erasing, writing, blank
455   checking, and retrieving processor ID and boot loader version numbers.  IAP
456   deals with primarily with sectors.  In the LPC2148 (which has 512K of flash),
457   there are 4K and 32K sectors.  The CCI will not allow selecting sectors that
458   are used for code.  The 'fss' command will find a safe sector to use with the
459   'iap' commands.  Once a safe sector is known, you can erase and fill this
460   sector.  The blank checking will work on any valid sector (there are 27 in
461   the LPC2148).  The IAP_COPYRAMTOFLASH (writing to flash) is demonstrated
462   by the fill command.  Whatever size the sector selected is, the 'fill'
463   command will fill the entire contents with the supplied byte value.  The 'md'
464   command can be used to dump the sector contents to see the effects of 'erase'
465   and 'fill'.  The 'stoa' command is used to convert a sector number to an
466   address for 'md'.  It is strongly recommended that you become familiar with
467   the section on IAP in the LPC2148 datasheet before using these commands.  The
468   IAP prepare and compare functions are not CCI accessible.  These are handled
469   internally by the erase and fill code.
470
471
472 MMC/SD notes:
473
474   As mentioned above, I have a Sandisk 64MB MMC card that the MMC drivers can't
475   seem to recognize.  I have 4 other cards that work fine, one of which is an
476   MMC, the other three which are SD.  I'd like to resolve this issue.  
477
478   During the 'thruput' test, when interrupts are left enabled, I have on rare
479   occasions seen a read or write error occur.  I believe this is because a
480   context switch is taking place during some time critical code.  
481
482   Ideally, interrupts would be disabled.  However, disabling interrupts makes
483   an RTOS merely an OS.  The 'real-time' part means predictable response to
484   interrupts, and the executing time-critical tasks on-time.  In this code, the
485   MMC/SD code is non-reentrant (only one task may read/write the card), and not
486   time critical.   If multiple tasks have to write to disk, this would
487   currently have to be handled by creating a task that communicates through
488   queues to other tasks, and manages the MMC/SD card.
489
490   Note that if a GPS is connected, a message that a NMEA checksum could not be
491   found may occasionally appear.  While the actual test is being run, the GPS
492   task is not processing messages, and the serial buffer overruns.  When the
493   task is allowed to run again (between tests), partial NMEA messages that
494   cannot be parsed may be present, resulting in the error message.
495
496
497 GCC notes:
498
499   This code was compiled with -O3.  This results in code that's about 16K
500   larger than -Os, but has a measurable impact on the MMC/SD card throughput
501   (not large, but it can be seen).  I went with -O3 because with 512K of FLASH,
502   and 144K or so used, there's plenty of room.
503
504   I'm not sure what the compiliation options for newlib are.  'crossdev'
505   compiled those, and I suspect it was with -Os, since embedded systems
506   generally tend to consider size over speed.
507
508   GCC is an amazing package.  I'm used to running into compiler issues with
509   many of the micros that I work with (SCCS, Microchips C18, etc).  It's so
510   nice to have a compiler that produces code without problems, and doesn't have
511   idiot front-ends that can't even get the sign on an enum correct (at least
512   Microchip got it right for the dsPIC and PIC24 parts, which used GCC.  C18...
513   Don't go there...)
514
515   There's a trick to writing Makefiles, and I don't have it.  It's an arcane
516   art, and involves the slaughtering of goats, black candles, and full moons.
517   The Makefiles I did write are very basic, and use recursion ('Recursive make
518   considered harmful!'.  Foo on that.  Worked for me).  
519
520   I tried a couple of approaches, and either everything built anyway, or
521   nothing built at all.  To make the linking work, as files are compiled,
522   they're dumped in to ./common/common.a, and main.c is linked against that.
523   So far, the expected bite on the butt for doing it this way has not happened.
524
525   It would be really neat to have Makefiles done right.  Alas, I don't know how
526   to do it right.  So if the common.a approach looks really ugly to you, that
527   means you probably know how to write Makefiles that handle sub-directories
528   correctly, and you can tell me how it should be done :)  (With examples!)
529
530
531 Notes on newlib:
532
533   I wasn't happy with the newlib syscalls.c that was included in the original
534   LPC2148 port.  I more or less completely rewrote this, with the exception of
535   _sbrk().  _open() can open the serial ports, USB port, and FatFS files.  All
536   supporting functions except _fstat() work (see FatFS complaint at bottom).
537
538   Newlibs method of converting a file descriptor (as returned by _open()) to a
539   slot (which points to assorted info for that fd) uses a loop.  As this is
540   done on EVERY read and write call, unnecessary overhead is added.  I fixed
541   the find_slot() code to cache the last fd, and if it's the same on a
542   subsequent call, the search is skipped.
543
544   _open() is VERY suspect, in that remapping of FatFS f_open flags don't
545   correspond cleanly to Unix's open() call.  I handle the four common cases
546   correctly, but lesser used ones may result in a EINVAL errno on open.  
547
548   Opening FatFS files is expensive, RAM space-wise.  Each open file uses a
549   FatFS FIL structure which contains a 512 byte buffer, plus some additional
550   space.  With 32K on a LPC2148, and 20K being used for the FreeRTOS heap, that
551   leaves 12K that has to be used for the stack, heap, printf(), etc.  Don't go
552   wild opening files, and be sure to close unused files to free the space.  Use
553   open() instead of fopen() whenever possible, as the FILE structure has it's
554   own set of buffers.
555
556   There may be a way to figure out how much heap and stack have been used under
557   newlib.  If there is, I haven't figured it out yet.  I'd really like to be
558   able to make a newlib or system call that returns total space available, heap
559   used and stack used. 
560
561   Since stdout and stderr point to same place, it's wise to close stderr and
562   set stderr to stdout.  Only functions like assert() use stderr, so
563   intermixing stderr and stdout shouldn't be a problem.  Especially since
564   there's no redirection of I/O...
565
566
567 Header file for LPC2148 (lpc210x.h):
568
569   The original LPC2148 header file was very lacking.  Not only were individual
570   bit fields generally not defined, major peripherials weren't defined.  As a
571   result, FreeRTOS, LPCUSB, FatFS and newlib all used local defines.  Worse,
572   some of these were simply "SOMEREG = (1<<31)".  Great.  What does bit 31 do?
573
574   Personally, I feel the best way is to define structures AND #defines.  It's
575   good that a structure has an element called 'CLK', but setting CLK to 0
576   doesn't give a hint as to what clock mode is being set.  A #define for
577   XXX_YYY_CLK_BIPHASE, then saying XXX_YYY_bits.ClkMode=XXX_YYY_CLK_BIPHASE is
578   a lot clearer.
579
580   I defined a mess of #defines, with the majority matching the names in the
581   datasheet.  There were few that become triplely redundant, such as
582   WD_WDFEED_WDFEED1.  This was reduced to WD_FEED_FEED1.  The characters prior
583   to the first underscore define the module, with the next set the defining the
584   register name.  Subsequent fields define the bit field name, and then
585   possible variations.
586
587   What I don't like about using #defines to define the registers is that the
588   programmer needs to know if the bits being affected need to be AND'ed or
589   OR'ed.  Structures neatly solve this problem, but defining all the structures
590   takes a lot of work (yea, IAR has already done that, but it's not legal to
591   just swipe their nice headers).
592
593   With one exception I'm aware of (in the TODO section), I rewrote all the code
594   that sets registers to use the values in the lpc210x.h file.  
595
596   While I doubt it makes the code more portable (will NXP change block
597   addresses, but leave bits the same?  Probably not), it does make it more
598   readable.  
599
600   One of the last major areas to be completed is to pull the USB protocol
601   engine #defines into lpc210x.h.  These are currently defined in one of the
602   USB header files, and have poor name scoping (does "ACK_STAT" tell you what
603   module or register it applies to?  No.)
604
605
606 Software notes:
607
608   All copyrights are by their respective authors.  FreeRTOS is by Richard
609   Barry.  LPCUSB is by Bertrik Sikken.  FatFS is by ChaN, with sections by Joel
610   Winarske.  Other sections of code may have come from the intarweb, and have
611   respective copyrights, indicated or not.  Any code that I personally authored
612   is free for public consumption, unemcumbered by any copyrights, etc (that
613   crap is just too confusing.  BSD? LPGL? GPL3?  Who the hell knows...)
614
615   I've re-formatted a good deal of code in LPCUSB and FatFS.  Some portions
616   were re-written, others simply re-formatted to my coding style (which I
617   jokingly refer to as JC1).  I have occasionally whacked comment blocks that I
618   didn't really think indicated what the code did, or was redundant.  I
619   probably whacked some text with copyrights in the process.  This in no way
620   reflects an attempt to claim the work as my own, or to otherwise dishonor the
621   original authors.  As Isaac Newton (more or less) said, "If I have seen a
622   little further it is by standing on the shoulders of Giants."  Without the
623   work of these most excellent people, this code would not exist.  
624
625   Most of the reason for my re-formatting is my way of understanding the code,
626   going through it section by section.  It's good because I have a better
627   understanding of it, worse because it makes drop-in replacement with updates
628   from the authors more difficult.
629
630   The most affected area is the SPI handling in the FatFS code.  Originally
631   named 'mm_llc_spi1.c', I felt this was not cleanly integrated, so I rewrote
632   it.  Maybe it's not better, but it is different :)
633
634   The FreeRTOS code is almost completely untouched, except for moving an #if
635   around that allowed compiling the trace code (configUSE_TRACE_FACILITY)
636   without requiring the task suspend code (INCLUDE_vTaskSuspend).  In the end,
637   this was probably irrelevant, since I compiled the task suspend code in
638   anyway.
639
640
641 Things I wish were different:
642
643   A collection of random little thoughts of things I wish were different.
644   These are just MY opinions, based on the way I do things.  It's not to say
645   the original authors were wrong.  It's just the way I'd make things, if I
646   were smart enough to write this stuff from scratch.  Most people probably
647   shouldn't even read the following list...
648
649   While FreeRTOS attempts to isolate the user from system data structures, it's
650   a little *too* aggressive.  These typedef'ed structures should be in a header
651   file, so applications can at least use sizeof() to help determine memory
652   allocation.  Everything is done through recasted void* pointers.
653
654   It would be neat if FreeRTOS had a xDelayTaskUntil() that also took one or
655   more queues as a blocking item.  I want to run a task every 'n' milliseconds,
656   but if something shows up in a queue, process it early.  Perhaps this could
657   work like Unix's select().  Or perhaps a variadic function that takes
658   xQueueHandles as parameters.
659
660   I dont' care for FreeRTOS's use of portBLAH typedefs for portable types.  The
661   world is pretty used to U8, U16, N32, and BOOL for unsigned char, unsigned
662   short, signed int, etc.  FreeRTOS also seems to require declaring too many
663   things as 'signed', which should be a default.  I'm sure this is done for
664   portability, but I find the types are not as intuitive as they could be.  
665
666   Another minor itch is that all function names and types start with 'x'.  I
667   would have preferred 'freertos', or better, a user-definable one, via a
668   #define macro.  I think programmers forget that their package may be
669   integrated into a larger system, and while their naming convention works well
670   for their purpose, it may not scale well.  FatFS and LPCUSB are guilty of
671   this as well.
672
673   FreeRTOS has a couple errors in several of the modules regarding type
674   punning.  I understand what type punning is, but I don't know how to fix it
675   safely.  Perhaps RB will fix those up in the next release.
676
677   FatFS changes return types too often, particularly for errors.  There's the
678   errors from the SPI routines, the MMC routines, the disk routines, and the
679   top layer FatFS code.  There should be unified errors for everything, so that
680   errors can be cleanly communicated up the stack.
681
682   FatFS can't go from file descriptor to filename.  I haven't figured out a
683   clean and reliable way to map a fd back to a filename (FatFS f_stat() needs a
684   file name).  I thought about malloc()'ing space in the openFiles_t structure
685   and copying the filename when the file is opened.  However, paths can get up
686   to 128 characters, and only _fstat() needs that information.  This seems very
687   wasteful.
688
689   FatFS wants the user to provid the get_fattime() function.  FatFS should
690   really have a file for locally provided functions.  It's already specific to
691   the SPI or IDE port implementation.  As such, it should be stubbed out to
692   return 0 if the function isn't provided, or allow the user to implement in
693   the platform specific file (basically, an equivalent of syscalls.c, but
694   internal to FatFS).
695
696   FatFS has naming conventions that I don't like.  It exposes too many internal
697   function names that should be declared static.  Structure names like 'FIL'
698   are ambiguous, and too likely to collide with other libraries.  Functions
699   should be preceed by the supporting module or library.  All FatFS functions
700   should be in the form of fatfsOpen, fatfsClose, etc.  
701
702   LPCUSB is not organized quite the way I'd do it.  The USB protocol engine
703   defines need to have their names modified and moved into the lpc210x.h. 
704
705   Newlib lacks certain calls on the ARM7 platform.  sync() and chmod() do not
706   exist, while mkdir() does, but wit no corresponding _mkdir() support in
707   syscalls.c.  Returning ENOSYS is easy enough, and doesn't take but a few
708   instructions.  Providing support for a wider range of calls would be good,
709   taking into mind things like FatFS that provide file system support, etc.
710
711   The Olimex board COMPLETELY lacks documentation (at least, that I've been
712   able to find).  It's up to the user to guess what the slide switches are for,
713   etc.  It's probably pretty obvious to someone who's used the LPC2000 parts
714   before, but if you're buying a board to get started, you have to waste time
715   figuring out how to use it.  Even a simple Xerox'ed sheet would have been
716   sufficient.
717
718   The Olimex board also lacks the ability to control the BSL line from the
719   serial port.  Reset works, but without being able to flip the BSL switch,
720   it has little value.
721
722   The buzzer on the Olimex board is useless.  Had it been connected to one of
723   the PWM outputs, some simple sound synthesis would have been possible.  At
724   best, it demostrates you can toggle I/O pins fast enough to make noise.
725   However, unless you want clicks in the output, you have to disable
726   interrupts.  And why *two* port pins?  One would have been sufficient.  I
727   would have preferred to have two more LEDs, rather than the buzzer.
728
729
730 TODO:
731
732   ./FreeRTOS/portable/GCC/ARM7_LPC2000/port.c uses local defines for timer control
733   Finish rest of syscalls.c functions (fstat ())
734   Some modules (USB) still have local #defines for hardware (protocol engine)
735   Add VIC software interrupt demo (?)
736   Add data abort demo
737   Frequency measurement?
738   Add fast GPIO (beep speaker)
739   Fix SPI code to be thread safe
740   Fix I2C using polled mode for EEPROM
741   Add firmware update from file system