Tuesday, August 4, 2015

My Own Dreamboard: FRDM-KL25Z Motion Data Logger Using MBED

P1020934.JPG


Introduction
Element14 has been running a competition for a DreamBoard and I was wondering how available some of the setups people are requesting are, to work this out I decided to do a simple project. The project goal was to use an ARM processor and incorporate a few sensors and store the data. After looking around I decided to go with the FRDM-KL25Z development board from Freescale and use the FRDM-STBC-AGM01 add on board. As there was no easy way to add an SD card I created my own board for that and at the same time added a battery monitoring circuit to make it a true stand alone unit. All the code was written using mbed to better feature the ARM processor on the FRDM-KL25Z.


Usage Case
The idea behind this project originated from two usage cases with essentially the same basic idea. As I work on equipment that needs to be ruggedized both from the elements as well as from handling, I thought what better way to understand what the equipment goes through than to log it. Its one thing to be told that something needs to stand up to rough handling and abuse but, if that abuse can be quantized it makes designing for the worst case that much easier. The second case and somewhat similar is shipping of fragile packages. It is possible to attach fragile stickers and shock sensitive glass vials but that would only tell you that a threshold force was reached but not for how long or how often or even when during transportation. An active motion logger would resolve all these unanswered questions. Both of these use cases would allow for the use of the FRDM-KL25Z with just one or two add on boards keeping the system simple and as close to a Dreamboard design as possible


Project Goal
Following these two usage cases mentioned above it was important to understand the main goals that this project setou to achieve. As both cases are looking at the handling of an object over a relatively short period of time (1 ~ 8 days) battery life was not critical, a custom battery/SD card board was built but that was mainly because it wasn't until later I found the Freedom Battery Charger Expansion Board. The custom board follows the design of the TI Fuel Gauge BoosterPack but with updated components. Another aspect of the project was price, as it is not known what the units are really exposed to in terms of  abuse, keeping the cost low would mean a damaged or destroyed logger would be no real concern in terms of replacement. Along the lines of a damaged or destroyed unit is the issue of data loss, should an event happen to cause a logger to be destroyed that event should, as much as possible, be recorded. Lastly the project should be implemented quickly and kept simple so that any issues that may arise or any requirement changes should be easily dealt with by anyone capable of understanding simple hardware/software.


Data Acquisition and Volume of Data
Looking to log data for 1 ~ 8 days without missing any abusive handling there was a need to establish how fast the system could sample data and store it without losing any of that data. It was decided by a pseudo scientific method that 50 Hz sample rate should be adequate. This was reached by assuming a falling object from one foot or so would take approximately 0.247s to fall, using 50 Hz would give approximately 10 data points on the way down allowing for an approximate drop height to be calculated as well as the force the unit experienced on impact (depending on the surface)


The accelerometer can log data in either 14 bits or 8 bits. Assuming higher resolution and therefore 14 bits that needs 6 bytes of data per sample or 300 bytes per second. The gyroscope also can log data in 8 or 16 bits and again using the higher resolution gives us 300 bytes per second. Since I2C can be set to run at 375 kHz, this would give a data transfer time of ~6.4ms. The I2C bus was eventually set at 400 kHz with a realistic clock frequency of 375 kHz.


Once acquired from the sensors, the data is stored on a SD card for later analysis.The SD card is written too using the SPI protocol which can achieve a theoretical 40 MHz. After some testing it was determined that the realistic speed for the FRDM-KL25Z programed using mbed was only 1 MHz, while very much slower than the 40 MHz desired it posed to be no issue for the setup. Using an 8Gb SD card the unit would be able to log data for ~154 days or well after the batteries are no longer working. This is estimated from 300 bytes/s for each sensor(8Gb / 600 bytes/s / 60s / 60m /24h = 154.32).


The battery life for this project is estimated to be 5 days using a 1200 mAh battery and the full power run current of 7.1 mA for the FRDM-KL25Z, 35 μA for the FXOS8700CQ sampling at 50 Hz and 2.7 mA for the FXAS21002CQR1. This gives a total current consumption of 9.835 mA and for a 1200 mAh battery that gives ~122 hours or ~5 days, if low power mode was implemented for the FRDM-KL25Z this could be further extended. This does not account for SD writes or other components on the boards.


Hardware Setup
The hardware consists of of three PCBs. The first board is the FRDM-KL25Z that contains the MKL25Z128VLK4 that is the brains behind the system and has the bootloader for the mbed environment.
xfrd_small.jpg.pagespeed.ic.6qSsxADs8d.jpg
Figure 2. FRDM-KL25Z Development Kit from Freescale


The second board is the FRDM-STBC-AGM01 this board houses the two sensors used in this project, the FXOS8700CQ is a 3 axis accelerometer and magnetometer and the FXAS21002CQR1 is a 3 axis gyroscope. The sensors both use the I2C and SPI protocols to communicate with the host processor. Since there are limited number of SPI modules on the host processor and the data rate of the sensors is relatively low the I2C module was selected. Another reason for this choice is the FRDM-STBC-AGM01 is configured for I2C and the the FXOS8700CQ only works with point to point SPI.

frdm-stbc-agm01_fig.1.jpg
Figure 3. FRDM-STBC-AGM01 Sensor Board from Freescale


The last board is an SD card connector breakout board like the DIGILENT  PMODSD  PERIPHERAL MODULE or the MIDAS  UNO32-SD  DAUGHTER BOARD. The board used in setting up this project was a breakout board from 43oh which was replaced by a custom board* that was designed specifically for the FRDM-KL25Z.


2015-07-28 00_46_46-1 Board - C__Users_Kasriel_Documents_eagle_projects_element14-projects-hardware_.jpg
Figure 4. Custom PCB Layout with Space for Both a SD Card & Battery Monitoring


The design of this boards borrows from the TI Fuel Gauge Boosterpack. The circuit is the same except for the BQ27510-G2 which has been upgraded to the G3. While the software for the BQ27510-G3 has not yet implemented when completed this will allow for the system to be truly stand alone and take precautions to ensure all data is saved before the battery is about to die.


P1020938.JPG
Figure 5. Custom Board with SD Card & Battery Management Circuit


P1020940.JPG
Figure 6. Custom Board with SD Card & Battery Management Circuit


While there is a expansion board from Freescale that has similar abilities, specifically the FRDM-BC3770-EVB, this board does not contain a SD Card slot and this board was only discovered after the custom board had be sent to the fab. The custom board includes both card detect and write protect pins to allowing the host controller to be sure there is an SD card available and in a usable state before starting the system.


P1020886.JPG
Figure 7. System Implementation Using Three Separate Boards


Software Outline
The software was written in a simple and easy to understand style to allow for anyone wanting to read over the or modify the code to be able to do so. For this reason the code follows a very simple progression as will be outlined below. The code was written in the mbed environment allowing for further simplification, at each stage in the flow diagram for the software there is some code that demonstrates what is required at that stage of the software flow. The full program can be found in the mbed repository here.


This project uses interrupt driven programming, this means that all events in the main loop only happen after an interrupt routine has set a flag signaling for the main loop to take action. Both interrupts that are used are fired when a sensors has recorded a preset number of samples in its FIFOs. When the interrupt occurs it sets a flag letting the mainloop know that there is data to be fetched from that sensors FIFO.


Figure 8. Interrupts That Drive the System


The first step in the code is to include the two libraries that are needed, mbed.h adds the basic functionality for the chosen platform and SDFileSystem adds the functionality for writing data to the connected Sd card. Once the needed libraries have been added, the registers used by both the FXOS and FXAS sensors are defined, this allows us to keep later I2C calls simple and self explanatory. The next step is to initialize the needed system modules.


Looking at the flowchart below we see the first module that is initialized is the serial port. This port is mainly used for debugging as it is a relatively slow port and in mbed serial communication is a blocking operation, it is therefore not desirable to use the serial port during high speed data acquisition. I2C is initialized to enable communication with the sensors and at a later stage the battery monitoring IC as well. The I2C port used is port PTE pin 0 for the data line (SDA) and pin 1 for the the clock (SCL).
Setting up the interrupts is a two step process, first we set pins to be interrupts in this project, pins PTD4 and PTA5 are set as FIFO full interrupts from the two sensors. The second step with regards to interrupts is done in the main function and that is to assign what to interrupt on (high -> low or low -> high transitions) and when an interrupt occurs what function should be called. In this case both interrupts are happen on a rising edge and they call functions called fxas_data and fxos_data respectively.


The last step in the initialization before going into the main function is to set up the Sd card communication. This is done by creating a SDFileSystem object and then giving that object the pins used for MOSI,  MISO,  SCLK and CS. In this project the default SPI port was used, PTD2, PTD3, PTD1 and PTD0 respectively. It has been verified that it is possible to use other SPI ports but for simplicity only one is pointed out on the platform pin descriptions.


After the initializations are completed the I2C clock frequency and serial baud rate are increased to allow for faster communications and reduced interruptions. For this reason the SDFileSystem used in this project has been modified to increase the clock frequency to 1 MHz to prevent the system from losing data during a SD card write cycle. The next step is to create a directory on the SD card in which to place or data and a file with heading. The last step in the main functions initializations is to set up and start the sensors, this is done by calling fxas_init() and fxos_init(). Once all these steps have been completed the system will start logging data.


FRDM-KL25Z System Initialization .jpg
Figure 9. System Initialization


The main loop runs in the background and does all the heavy lifting. The first step in the main loop is to look for a FIFO full flag set in one of the two interrupts. Once a flag has been set the main loop will read all available data samples and store them in a local buffer. This buffer was arbitrarily set at 23, for better performance and possibly longer sleep times by the processor this could be set to 30 or 32 samples. When all the samples have been read from the sensor a data ready flag is set, this flag indicates to the next step of the main loop that data is ready to be sent to the SD card.


After data from both sensors has been read in, which should happen very close in time as both sensors are running at 50Hz, the main loop will send all available samples to the SD card. To do this correctly and in somewhat of a understandable fashion the MSB and LSB of each sample are concatenated before sending the data to the SD card. As the accelerometer data is 14 bits long and the LSB is left justified, there is a need to first shift the MSB left by 8 bits then OR the two bytes and finally right shift  all 16 bits by two to arrive at 14 bits of data. As fractional operations are  computationally heavy on microprocessors multiplying the data by either 0.976mg or 7.8125mdps has been left to be completed on the PC.


Once all data has been sent to the SD card the file is closed, this is done once every 30 cycles to ensure minimal amounts of data are lost. It is not done more frequently as this adds extra overhead to the SD write cycle. After closing the file the buffers are cleared, while not essential this was done to remove any question as to the correctness of the sampled data.


FRDM-KL25Z Main Loop.jpg
Figure 10. Main Loop Where the Time Consuming Operations Occur


The software in its entirety can be found here, the project can be added to your project space and then downloaded to your own FRDM-KL25Z from that location.


MBED
As part of this project was to show of the ARM core at the center of all the processing, the mbed environment was used. Along with showing of the ARM core mbed also allows for implementing programs in relatively simple and quick ways to be used as a prototype or in some circumstances for get to the final product quickly. While using mbed for this project I realized the ease with which other wise long and complex tasks can be achieved. Setting up interrupts and along with what action should be taken when fired only takes two lines. Similarly setting up the SD file system also takes two lines of code.


That being said there are some thing to watch out for. During this project I was not able to use the blue LED for debugging, this was discovered only after I was no longer able to save data to the SD card. It was later noticed that the SD card clock and the blue LED are on the same pin. Other issues where setting clock frequencies. The clock for the SPI but does not appear to be able to be set above 1 MHz, while I have tried a few different ways to reach this I was not able to do so. The same issue is noticed with the I2C bus, going above 375 kHz does not appear possible, I was hoping to achieve 400 kHz but setting the frequency higher only seems to decrease the clock frequency after a certain point.


Also not having a built in debugger when you are used to depending on one is a huge change in the game. Another big change that may take getting used to is the bootloader. Where with a conventional IDE there is a one step compile and program, here there is a two step compile and download and then drag and drop into the platform. While not a huge game changer it does slow down the programing iterations. Both of these may have bothered me but in a weird way I feel doing more programing like this would make you a better programmer as there is a need to do this better and in a more thought out manner the first time and less by trial and error.


With a few issues encountered along the way there is one very big positive to mbed. There is a large and very helpful community. No matter how big, small or subtle the issue I found that the community was both willing and very capable of helping.


Project Testing and Usage
The project while on a basic level is complete this is room for further progress. At this point there is a need to use the project to log how a package that is shipped is handled so as to better understand the design constraints to build a resilient outer shell.
In order to use this unit in a somewhat meaningful way the data obtained from this project is put through a graphing program to determine how the unit has handled. My program of choice is GNUPlot or Excel. While Excel has a limitation on the number of points it will plot for you (1048576) GNUPlot does not. Below I have included data samples from some test with this project to give an idea of what the project is capable of.


2015-07-28 13_42_20-Gnuplot (window id _ 0).png
Figure 11. Accelerometer Data Recorded on a 15 Minute Drive


2015-07-28 13_41_04-Gnuplot (window id _ 0).png
Figure 12. Gyroscope Data Recorded on a 15 Minute Drive



Issues experienced and their resolutions

Pin mapping and peripheral usage

FRDM-KL25Z not capturing Interrupts

Non-blocking interrupts

Arithmetic or Logical Shift in mbed

SDFile system working in standalone but not with other code

Logical operator frustrating me


*Rev A of the board is on branch Board_Inverted and not on the main branch at this point in time.




Original post on Element14 can be found here

Friday, March 13, 2015

Sudden Impact Challenge - Blog Entry 4

This past week or so has produced some promising movement as well as some valuable learning experiences, I will outline these below.


ADXL362 Dead
As noted in Blog Entry 3, I have been working to get the SPI working in a useful and simple format. While working on this there were issues in determining if it was the code or the ADXL362 that was not working correctly. This is where the first lesson was learned, the true value of simple and cheap test equipment. By simply connecting the breakout board to a Bus Pirate ($30) it was a simple matter to determine that it was the breakout board (I assume the ADXL362 itself and not one of the caps) was no longer working. This simple test board paid for itself just in removing aggravation and showing where the issue truly lay.


While I thankfully I have another breakout board from a previous project I am still unsure as to why this breakout board has stopped working. The connections between a previous test and the test that appeared to break the board where the same. In fact the board had been working over night and only the next morning did the board give up the ghost. Maybe after the challenge is over I will see about determining the real issue and possibly replacing the ADXL362 on the board.


Getting SPI Working
This leads to the second valuable lesson, the true value of demo code. While the CC3100 uses the SPI module and works well and the datasheet for the MSP430F5529 is pretty well written there were still issue getting the SPI working correctly for the ADI devices. TI has demo code for all the modules on the MSP430F5529 which gives a good starting point to get your code up and running. Again, here the Bus Pirate came in handy, the ADXL362 registers were returning values that differed from the datasheet, particularly the REVID, XDATA and STATUS. This was lead be to be a bit uncertain with the code I had written. I therefore again used the Bus Pirate to verify the correctness of these values. It should be noted that for all of the SPI testing the Saleae Logic was used to read the values sent and received to the ADXL362. Although there is now a new version I have found this to be an indispensable piece of test equipment that now together with the Bus Pirate has saved many hours of debugging.


Another interesting lesson learned was time delays in the SPI protocol or at least with the ADXL362. During some debugging there appeared to be an issue that I thought a longer delay could resolve or at least shed some light on so the delay between sending and receiving data was increased to ~100 clock cycles (for i < 100). Once this was done the ADXL362 stopped responding. Using the Saleae Logic analyzer it was easy to see that the only difference was the timing, while no information could be seen ADXL362 datasheet and in theory the time between sending bytes to the device is not constrained the long durations (1.17 ms vs. 0.56 ms) was not liked by the ADXL362.


SPI Logic
The last issue encountered with the SPI module was using an inbuilt delay between sending or receiving multiple data bytes. Working from the CC3100 demo the code implemented was as follows


while (!(UCA0IFG & UCTXIFG)); // USCI_A0 TX buffer ready?
UCA0TXBUF = 0xFF; // Transmit first character
while (UCB0IFG & UCRXIFG); ← Logically useless….
RxData[j] = UCA0RXBUF;


Logically this does not make sense, according the the datasheet  URXIFG = 0 when no interrupt pending, therefore in the above case as long as an interrupt is pending the code should remain in the while loop and NOT service the RXBUF. What should work but doesn't for some unknown reason is ”while (!(UCB0IFG & UCRXIFG));”. With this logic the program reads the RXBUF only once and then appears to freeze without spending too much time on it I was not able to find a root cause for this. I would assume that somehow when UCTXIFG is read and therefore cleared UCRXIFG is also being cleared.


While this appears to work for the CC3100 I can only assume that the time RXIFG never gets set in this case possibly because the RX happens at the same time as the TX. I have not checked the errata for the MSP430F5529 but will possibly do so at a later date.

Note: It just occured to me that the code actually reads UCB0IFG which includes BOTH UCTXIFG and UCRXIFG thereby clearing both of them. While I a not sure if this is correct appears somewhat plausible. The only issue is that the same code still works for the CC3100 with no apparent issues, but that may have something to do with timing and that the CS pin goes high between a Tx and RX in that case.

ADC
Work on the ADC has also begun this week. While the sample code does yield some results it has so far proven unreliable but a starting point nonetheless. For further testing to again check the response as well as to get a better understanding of the ADXL377 (high g analog accelerometer) was connected to an oscilloscope to check responses and behaviour of the device. As of yet there appears to be an issue hopefully with the oscilloscope as the understood response should be ~1.5 V at 0g - 1g which is not was displayed on the oscilloscope. The oscilloscope used has been showing some issues (NOT the oscilloscope provided with the SIC kit but one at work) so hopefully when I can make some space on my desk I will breakout the new oscilloscope and test the part with that.Hopefully with the new oscilloscope a clearer understanding of how the ADXL377 works will be achieved as well as how to better interpret its output.


Next Steps
The next major step is to get the ADC on the MSP430f5529 working so that all three channels of the ADXL377 can be read and possibly the three channels of the AD8232 (Heart Rate Monitor Front End) working as well. Once this has been completed and well tested both the SPI code and the ADC code will be integrated into the overall project code and tested to ensure no functionality in the project code has been lost or corrupted.

Monday, March 2, 2015

Sudden Impact Challenge - Blog Entry 3

The past week has been spent trying to get a reliable SPI connection between the MSP430F5529 and the Analog Devices sensors as well as mapping pin connections for all devices needed for this project.

SPI Connection
The initial design plan was to use one SPI module for all SPI devices, this would include the CC3100 as well as the accelerometers and temperature sensor. The spi.c file was altered to allow for multiple device selects and all code was changed through the tcp_socket demo project. Once this was cleaned up and compiling with no issues the code was tested with the CC3100 and found to be working reliably. The next step was to attach a second SPI device.

At this point interesting things started to happen. When the ADXL362 was connected as it should be (MISO <->MISO, MOSI<->MOSI…) the CC3100 no longer worked, however, switching the connections (MISO <->MOSI, MOSI<->MISO) the CC3100 proceeded to work again. Using a logic analyzer it was clear the SPI was communicating in both cases but possibly not correctly (clock ticks were missed due to sampling rates of the old Saleae Logic) . It was also pretty clear from the sample data that the SPI frequency was set to 12 MHz. Once this was discovered and realizing it was not a hardware issue (verified using a Bus Pirate to talk to the ADXL362) the datasheet for the ADXL revealed the clock speed for the device MUST be between 1 MHz and 5 MHz (or 8 MHz depending on datasheet version). The Plan now is to write a new SPI driver for the ADI devices that will run at an acceptable clock rate for ALL the needed devices (ADXL362 1MHz - 5MHz, ADXL375 < 5 MHz, ADT3720 - Unknown). Once reliable communication has been established correct interpretation of input data will be worked out to enable proper interpretation and use of sensor data.

UART Code Removal
Also this week, time was spent removing code to control the CC3100 via UART. This was done to increase code readability and to remove possible confusion within the code. This was also done to help identify unused pins that may be used for the UART control of the CC3100. During this process the overall understanding of the code was greatly increased.


Pin Mapping
Since there was no clear indication of what pins were free, a quick code review was done to find all used pins and what they were used for. This was done to find all available pins and to correctly detail the used pins. As can be seen in the table below the CC3100 has a lot of pins broken out but only six are used. There are four for SPI, one for interrupts and one to enable and disable the CC3100, this excludes the 3.3 V rail and ground.

Once these were eliminated from the list six analog pins were selected, these would be set aside for the ADXL377 and time permitting the heart rate monitor. These were chosen next as there are only a limited number of analog pins on the MSP430F5529 and it was preferable to try have them consecutively numbered to potentially allow for easier programing.

Once the analog pins were selected the SPI for the ADI devices and their chip selects were chosen. All pins assigned so far can be seen in the table below.

Table 1. Pin Mapping For MSP430F5529 & CC3100

Next Steps
This coming week will be spent getting all SPI devices working correctly and reporting back some data (Device ID) and formatting that data correctly. Once the SPI modules are working correctly and their data is correctly interpreted the ADC module will be attempted.

It may be obvious by now, but the user interface has been neglected at this point due to complexity in the learning curve for QT. For now data will either be sent to plot.ly for plotting at a decimated rate or logged on a local computer in a not athsetic interfcae, something like a terminal.