Sunday, June 14, 2015

AMS00x BLE Module

I found this little guy while looking for parts on Mouser the other day:
 
It's a $6.50 certified BLE module from ACKme Networks based on a Broadcom ARM Cortex-M3 SoC! The module breaks out the ADC, USART, SPI, I2C, PWM and GPIOs and ships with a pre-loaded firmware called TruConnect that lets you control the module via the serial port.

They also have a dev board, with switches, buzzer, RGB LED, accelerometer, switching regulator and an FTDI chip great for quick evaluation but It's a bit expensive and there's a jumper on the backside! I had to buy one anyway because the module was not stocked yet, but I'll be getting the modules next time.
ACKme also released an iOS and Android apps for quick testing, the  iOS app has more features, it lets you read the ADC and switches, use the serial interfaces and upgrade the firmware OTA. However, I don't have an iOS device so I just used the Android app to connect to the module and blink the LED:


I made a quick breakout board for future modules, you can order it directly from OSHPark or checkout the repo if you don't need a dev board. Note: This breakout is Not tested!


Read more ...

Saturday, March 14, 2015

THP 2014/2015, OpenMV, Kickstarter and Pi Day!

It's been a while since I last wrote about anything, been very busy with THP, Kickstarter, new projects and day dreaming (more on that later), also I've been documenting OpenMV mostly on Hackaday.io

However, today is a very special day, it's Pi Day of course, but it’s not just any Pi Day, today at 9:26:53 will describe Pi up to 10 digits, yay!  Something that happens once in a lifetime, and if that's not enough, today marks exactly 5 years since my very first blog post and it also happens to be my birthday ;D

Not being able to resist this historic day, I had to write something, so here's a long overdue post in which I'll try to document my experience with all this stuff, and share with you some of the lessons I've learned along the way.

THP 2014
Last year I submitted OpenMV for THP, I clearly remember saying to myself "Well, here goes nothing" and then I clicked submit, and bang it went viral! I received lots of comments, feedback, orders, even a few job offers!
Shortly after that, OpenMV became the second most "Skulled", viewed and commented project on hackaday.io (and still is, so far). Even though I did not make it to the finals at the end of it, but overall, I think joining the contest was one of the best things I ever did.


Hint: Just put your project out there, you have nothing to lose, try to document a lot, and if you're lucky, lots of awesome people will give you feedback and support.

Prototyping
Having received lots of request for cameras, with the help of my friend Michael Shimniok we (well, mostly just him :D) went ahead and made a small prototyping run, just to see how things go before doing anything serious:

 
This was the original OpenMV cam in the photo, we only made about 20 units of these, the biggest issue was Windows support, which had me recently sit down and rewrite the whole debugging interface to use CDC and, sadly, ditch libusb all together (it's a shame because I enjoy coding with libusb) I might document this issue here one day.

Hint: plan and *test* cross-platform support as early as possible, before anything else, if you want that eventually (in my defense I didn't want to support Windows at all when I started)

20 cameras were sold on Tindie, and we had more than 100 backorders, at this point, we decided to move forward and seriously consider mass production (by "mass" I was thinking 500-1000 units)

Production
Making a product is no picnic, everyone knows that, you have to consider many factors when doing more than a few prototypes, from parts sourcing, programming and testing to order fulfillment and support, then there's always some product-specific issues that might catch you off guard, something as simple as focusing the lens!

At this point small costs start to creep in and If you're not careful enough or don't know what you're doing, something is bound to go wrong, and you might end up loosing money instead making profit.

One option is to outsource the whole thing to someone, and that's exactly what we did to minimize risks as much as we could, we've been in contact with MacroFab and decided to go with them, they'll be taking care of everything, I have to say I'm still impressed with the idea of a whole production backend as a service :)

On my end of things, other than working on the software, I went through a few designs trying to find that perfect balance between features, cost and "manufacturbility".

Some of the things that I've encountered may (or may not) surprise you, I found out that a cheaper connector or sensor might end up costing a lot more to assemble and test, so unless you plan on assembling 1000s of something yourself, think very carefully which parts you want to use, and consider the costs of assembling and testing those parts.

I finally settled on the latest hardware seen on the Kickstarter and then designed a small programming/testing jig, which I'll keep working on and improve further, if needed, in the following days.

Hint: think very carefully which parts you want to use, and consider the costs of assembling and testing those parts.

Kickstarter
This brings us to funding and the Kickstarter, although we've been planning this for a while but it obviously was not enough, I think we did great and all (900 backers/208% funded) but we could have done much better (with some more planning and time) but that's okay for a start :)


If I learned anything from this KS, is that one should plan on every little detail before starting, this the best advice I can give anyone who wants to do this, plan and then plan some more, this includes reward tiers, stretch goals, content, logos, even updates timing and post-KS sales!

Hint: Be prepared for post-KS sales, have a website up and running, ready to receive back orders as soon as the KS ends (A lesson painfully learned as we still can't accept backorders yet :( )

THP 2015
Moving on to THP 2015, which just launched a few days ago, I've been eager to participate this year too, if for no other reason than the excitement of it :) sadly, I'm not sure I'll have the time this year and so far I don't have any worthy ideas (well maybe I have one or two tucked away ;))


This year's theme is about solving important world problems, some folks like this theme, personally I believe the world is doomed and I can hardly solve my own problems :) but I am still interested, also there's something new this year "The Best Product Prize" a grant of sorts to bring your product to the market, which sounds great.

If you have an idea go ahead and sign up, you do have a chance (not to save the world of course) but you'll get exposure for your project and maybe you'll win some cash too ;)
Read more ...

Wednesday, July 9, 2014

Using the STM32 DCMI with JPEG Sensors

If you've been looking for this, chances are you saw Frank's post on the subject, while it contains very useful information and he mentions reading JPEG, he didn't explain his approach in details, so here's my soultion.

First, let me reiterate the issue with JPEG and the STM32, as you already know JPEG images are compressed, so you don't know the exact image size beforehand, you expect to read it after a complete transfer, however, the STM32 DMA data count register (NDTR) counts down, and therein lies the problem, the counter reaches zero after a complete transfer (or gets reloaded in case of a circular mode) either way, you can't find the transfer size after a DMA transfer is complete.

So here's my solution to this problem, first set the DMA stream to transfer the maximum frame size you expect or the absolute max for a DMA transfer (2^16 bits), afterwards, start the DCMI, it will generate a FRAME_IT when a whole frame has been read (VSYNC is asserted high/low depending on the polarity) however, the DMA will never stop, so at this point you should abort the DMA transfer, this will leave the remainder of the transfer size you requested earlier in the NDTR register (it's guaranteed to be there because the transfer was interrupted) now subtract that from the initial transfer size and you have the frame size.

Here's an example code, which uses the STM32Cube (HAL):

uint32_t addr;
uint16_t length;

addr = (uint32_t) image->pixels;
length = MAX_XFER_SIZE;

/* Start the DCMI */
HAL_DCMI_Start_DMA(&DCMIHandle,
        DCMI_MODE_SNAPSHOT, addr, length);

/* Wait for frame */
while ((DCMI->CR & DCMI_CR_CAPTURE) != 0) {

}

/* The frame is finished, but DMA still waiting
   for data because we set max frame size
   so we need to abort the DMA transfer here */
HAL_DMA_Abort(&DMAHandle);

/* Read the number of data items transferred */
image->size = (MAX_XFER_SIZE - DMAHandle.Instance->NDTR)*4;
One issue remains, what if it overflows ? well that would mean you're really cutting it close, but anyway (I haven't tested this) but you should be able read the overflow flag in the DCMI port, or check the JPEG markers.
Read more ...

Tuesday, June 3, 2014

OV9650 Breakout

I made this breakout for the OV9650 a while ago, and I've been waiting to test it before sharing, I finally had the chance to do so, I used an FPGA this time for testing, and here's the result:


The breakout has two SOT23 LDOs for the sensor's core, digital and analog supplies and requires a single external 3.3v supply, note that most sensors have internal regulators for the core supply, so technically you only need one, anyway, those LDOs should be fairly easy to source, their exact voltages depend on the sensor used. The board is compatible with a few other Omnivision sensors, such as the OV9655, OV7660, OV2640 etc... however, make sure it has the same pinout...

Here's the breakout and Eagle library:
https://github.com/iabdalkader/OV965x

Alternatively, you could order the PCB directly from OSHPark:
http://oshpark.com/shared_projects/FQwlpPpi
Read more ...

Saturday, April 26, 2014

Running ZPU Softcore on Lattice ICE40

So I got my hands on a new FPGA development board, a Lattice ICE40HX8K eval kit, this is a really basic low-cost board/breakout with a few LEDS, EEPROM and a dual FTDI2232H UART/FIFO, that you can use for programming the EEPROM/FPGA...What I really love about this board, other than the low cost and many I/Os, is that the second FTDI port is configured as a serial port and connected to the FPGA, so basically you get a free USB<->USART bridge which you can use to talk to the FPGA with the same USB cable used for programming (see Linux notes) that's basically all I need as I'm already familiar with FPGAs...
I wanted to evaluate those FPGAs for a new project I'm working on, which will most likely require a minimal SoC with a wishbone bus... My first thoughts was to use my uMIPS core, but it doesn't support the wishbone bus (I might fix that later) so I decided to give the ZPU core a shot, which was definitely worth the time it took to get it working on the Lattice FPGA.

In an effort to save someone else's time, I created this github repo for the project, it has the sw, hdl, project files and a tested bitmap file, all you need to do is to program the bitmap (or synthesis the project with iCEcube2 if you want), open /dev/ttyUSB1, set it to 8N1, 9600, parity=none and reset the core (you will need and external switch for that, connect it between H16 and GND), it should print out "Hello World!"...

ZPU Core:
The ZPU is small 32-bit stack-based CPU, it comes with a gcc-toolchain, lots of variants and examples... For this project I used the zealot/medium variant which comes with a physical I/O layer (provides a USART, GPIO and a timer) and I'm using a single port RAM, no PLLs (to keep things simple) and all the RAM blocks on the ICE40HX8K (16KBs total) for the program image. There's no wishbone yet, I will work on that next.

Compiling Stuff:
First It's worth mentioning here that I modified the I/O memory map (crt_io.c) since there's only 16KBytes of on-chip ram, I modified it to use bit 15 for the I/O space, the modified crt_io.c is included in the repo and the Makefile will compile and link this modified map for you.

If you want to compile a new program, you'll need to download the ZPU toolchain first and use the Makefile in zpu/sw it will generate a bunch of files, the one we're interested in is hello.bram, this contains the instructions/data used to initialize the embedded RAM, copy the contents of this file and replace the one in bram.vhdl.

Linux notes:
I didn't have much trouble getting the software running on Linux, but one thing you might want to do to make things nicer, is to use this udev rule to unbind ftdio-sio from the first FTDI port when the board is connected, this will allow the programmer to use the first port as JTAG with the second (USART) port bound to ftdi-sio at the same time, so you can use it as to talk to the FPGA after programming:

BUS=="usb",ACTION=="add",SYSFS{idVendor}=="0403",SYSFS{idProduct}=="6010",MODE=="0660"
,GROUP=="plugdev",SYMLINK+="ftdi-0"
SUBSYSTEM=="usb",DRIVER=="ftdi_sio",ATTRS{idVendor}=="0403",SYSFS{idProduct}=="6010"
,ATTR{bInterfaceNumber}=="00",RUN+="/bin/sh -c 'echo `basename %p` >/sys/bus/usb/drivers/ftdi_sio/unbind'"

The following is the iCEcube report for this design:

Total Logic Cells: 3099/7680
Combinational Logic Cells: 2471     out of   7680      32.1745%
Sequential Logic Cells:    628      out of   7680      8.17708%
Logic Tiles:               473      out of   960       49.2708%
Registers: 
Logic Registers:           628      out of   7680      8.17708%
IO Registers:              0        out of   1280      0
Block RAMs:                32       out of   32        100%
Pins:
Input Pins:                3        out of   206       1.45631%
Output Pins:               9        out of   206       4.36893%
InOut Pins:                0        out of   206       0%
Global Buffers:            6        out of   8         75%
PLLs:                      0        out of   2         0%

Read more ...

Saturday, February 8, 2014

OpenMV Update: MicroPython, More I/O, uSD and Lots of Other Things!

Time for another update, sorry this took me so long, I've been very busy working on OpenMV, the good news is I have lots of new features implemented! There's a new (smaller :D) hardware revision with more I/O (USART/I2C and SPI) and a uSD socket, MicroPython support, an IDE for the camera, and for those of you who have been wondering, I'm working with Michael Shimniok from Bot-Thoughts on doing a Kickstarter campaign for OpenMV, soon, hopefully, you will be able to get one for a very reasonable price :) so stay tuned!

Okay, so on the software side, you've probably heard of the MicroPython project, if not make sure to check it out, basically MicroPython is very efficient, lightweight Python VM for microcontrollers, the plan was to script the camera with Lua/eLua but MP has some really neat features already implemented, so long story short, I've decided to script the camera with MP... after lots of work, I managed to get MP running on OpenMV, and wrote some MP bindings to export the subsystems of OpenMV to Python, eventually it will be completely controlled with Python.

So how this works so far, basically, on reset OpenMV runs a default Python script with the old serial camera interface (receive commands from the serial port, process and return result) but it also shows up as a small USB storage device where you can copy your own Python script(s), reset and it runs that instead of the default script.. In addition to that, you can also "talk" to the camera directly using a Python shell over the com port while watching the framebuffer in realtime :)

I've also combined all those nice features into a single "IDE" for convenience, written with Python, PyGTK and PyUSB. The IDE has a Python shell, a framebuffer viewer, and it can run scripts or save them to flash:


Moving on to the hardware, the new revision is 1.0x1.30 inches, it has a tiny uSD socket (which will be available to Python user code) USART, SPI and I2C broken out on the main 2.54mm header and a separate 2mm SWD debugging header.. There's also a switch, which will be used for boot or reset.
Here are some pics of the 3rd (2nd?) revision:



Compared to the old one:



That's it for now, please let me know if you have any comments :) thanks!
Read more ...

Saturday, January 18, 2014

Overclocking the STM32F4

I've been doing some tests with the STM32F407 to see how fast it can go, STMicro has released an almost identical one that runs at 180MHz, is it a marketing thing ? will they release a 200MHz version in a few months? who cares, anyway, I was able to run the STM32F407 at 240MHz without any "obvious" problems, in addition to overclocking, the code listed below lets you set some different frequencies, which could be useful for frequency scaling.

On the STM32F4 the clocks are controlled via the RCC (Reset and Clock Control) block, it's easy enough to change the frequency, the tricky part however, is understanding all the different dividers and getting them right. According to the datasheet, the following are the maximum clock frequencies for the core and peripheral buses:
SYSCLK: 168MHz
PLLC48: 48MHz (feeds the USB OTG FS and RNG)
APB1 clock: 42MHz
APB2 clock: 84MHz
Based on that, I used multiples of 42MHz to get the maximum possible frequencies for the peripheral buses (APB1 and APB2) for frequencies lower than 168MHz (this doesn't always result in the maximum USB frequency, which is required to get the full 12Mbps), for frequencies higher than 168MHz, I used 200MHz and 240MHz mainly because they are convenient to my application, you might want to use different frequencies based on yours:
enum sysclk_freq {
    SYSCLK_42_MHZ=0,
    SYSCLK_84_MHZ,
    SYSCLK_168_MHZ,
    SYSCLK_200_MHZ,
    SYSCLK_240_MHZ,
};

void rcc_set_frequency(enum sysclk_freq freq)
{
    int freqs[]   = {42, 84, 168, 200, 240};

    /* USB freqs: 42MHz, 42Mhz, 48MHz, 50MHz, 48MHz */
    int pll_div[] = {2, 4, 7, 10, 10}; 

    /* PLL_VCO = (HSE_VALUE / PLL_M) * PLL_N */
    /* SYSCLK = PLL_VCO / PLL_P */
    /* USB OTG FS, SDIO and RNG Clock =  PLL_VCO / PLLQ */ 
    uint32_t PLL_P = 2;
    uint32_t PLL_N = freqs[freq] * 2;
    uint32_t PLL_M = (HSE_VALUE/1000000);
    uint32_t PLL_Q = pll_div[freq];

    RCC_DeInit();

    /* Enable HSE osscilator */
    RCC_HSEConfig(RCC_HSE_ON);

    if (RCC_WaitForHSEStartUp() == ERROR) {
        return;
    }

    /* Configure PLL clock M, N, P, and Q dividers */
    RCC_PLLConfig(RCC_PLLSource_HSE, PLL_M, PLL_N, PLL_P, PLL_Q);

    /* Enable PLL clock */
    RCC_PLLCmd(ENABLE);

    /* Wait until PLL clock is stable */
    while ((RCC->CR & RCC_CR_PLLRDY) == 0);

    /* Set PLL_CLK as system clock source SYSCLK */
    RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK);

    /* Set AHB clock divider */
    RCC_HCLKConfig(RCC_SYSCLK_Div1);

    /* Set APBx clock dividers */
    switch (freq) {
        /* Max freq APB1: 42MHz APB2: 84MHz */
        case SYSCLK_42_MHZ:
            RCC_PCLK1Config(RCC_HCLK_Div1); /* 42MHz */
            RCC_PCLK2Config(RCC_HCLK_Div1); /* 42MHz */
            break;
        case SYSCLK_84_MHZ:
            RCC_PCLK1Config(RCC_HCLK_Div2); /* 42MHz */
            RCC_PCLK2Config(RCC_HCLK_Div1); /* 84MHz */
            break;
        case SYSCLK_168_MHZ:
            RCC_PCLK1Config(RCC_HCLK_Div4); /* 42MHz */
            RCC_PCLK2Config(RCC_HCLK_Div2); /* 84MHz */
            break;
        case SYSCLK_200_MHZ:
            RCC_PCLK1Config(RCC_HCLK_Div4); /* 50MHz */
            RCC_PCLK2Config(RCC_HCLK_Div2); /* 100MHz */
            break;
        case SYSCLK_240_MHZ:
            RCC_PCLK1Config(RCC_HCLK_Div4); /* 60MHz */
            RCC_PCLK2Config(RCC_HCLK_Div2); /* 120MHz */
            break;
    }

    /* Update SystemCoreClock variable */ 
    SystemCoreClockUpdate();
}

Note: after calling this function, you will probably need to re-enable all the clocks ...

Note on Overclocking:
There's no telling if overclocking will always work, it might fail at some temperature, critical path or just randomly, but it is nice to know that you have the option to run (burn?) the micro at higher speeds if needed... One thing I can confirm though, is that it doesn't overheat too much, obviously touching the micro with your finger tip is not an accurate way to determine that, so I took this a step further and made a series of tests using the internal core temperature sensor.

I ran the micro at different frequencies while collecting samples from the internal temperature sensor, which is connected to one of the ADC's channels, for each frequency I collected a number of samples and then I plotted the average vs the frequencies and here's the result:
One important thing to note here, the internal temperature sensor readings varies from chip to chip up to 45 degrees, which means those are NOT absolute temperature values but should only be used to detect temperature variations. Now, the conclusion, it looks like overclocking the STM32F4 from 168MHz to 240MHz increases the core temperature by ~4 degrees.
Read more ...

Thursday, December 5, 2013

OpenMV Update: 25FPS Face Detection, USB Support and More

So I've been working on OpenMV for the past week and this is what I have so far:

USB Support:
The camera now supports USB OTG full speed, I've also written a small userspace tool with libusb/SDL to interface with the camera and view the frame buffer, this makes it really easy to debug the image processing code, and it also lets you change the sensor's registers while watching the results in realtime.


I've mentioned building the STM32F4xx libraries in a previous post, you can checkout the repo linked there if you want to build the libraries.

Face Detection:
Many were very interested in this feature, well I've managed to get the viola-jones face detector working on the camera, and it's working fine.. For those of you familiar with the detector, the haar cascade is exported as a C header which is linked to the binary and loaded into the CCM (Core Coupled Memory) a 64KB memory block connected directly to the core. Only one integral image is pre-computed and allocated on the heap, the other one, the squared integral image, which is used for computing the standard deviation, can't fit into memory for the QQVGA resoultion, and so, instead, the standard deviation is computed on the fly for every detection scale using some SIMD instructions to speed it up a bit.


The memory can hold up to 23 stages, however, using only 12 stages and with a relatively large scale step, the detector is working great, with occasional false detections of course, more stages can be used if greater accuracy is required, but not without some performance penalty...As for the numbers, the camera can process 7-8FPS QQVGA, and for QQCIF (88x72) I get 25FPS! 

Here's a video of the face detector in action running at 25FPS:


Here's another video of color tracking running at 30FPS:


Other Updates:
I've been doing some general fixes here and there, mainly to improve the image quality, in addition to that, I've compiled all the libraries and code with optimizations (-O2) and I've seen great improvements in speed, there's also a new pixel format, grayscale, which is basically just the Y channel extracted from the YUV422 to avoid doing that every time a grayscale image is required.

The QCIF/QQCIF are working now (the sensor can output 60FPS when using QQCIF ) and through some other register probing, I've removed a few useless registers and discovered that the sensor has digital zoom, cool!

There's also simple motion detection code in progress, it's based on frame differencing and using the first frame as the background, more work will be done here as soon as I get around to it. And I will probably try template matching next.


I've also just finished a new hardware revision, it has a tiny uSD socket, which I imagine can be used for anything from storing haar cascades, snapshots or video to buffering larger frames, the new revision is also a bit smaller. 
Read more ...

Monday, December 2, 2013

Using The CCM Memory on the STM32

The STM32 series have non-contiguous memories divided into blocks, for example the STM32F4, has 2 (contiguous) blocks of SRAM connected to the bus matrix with different interconnects, and a Core Coupled Memory (CCM) block which is connected directly to the core.


This tight coupling of the CCM memory to the core, leads to zero wait states, in other words, the core has exclusive access to this memory block, so for example, while other bus masters are using the main SRAM the core can access the CCM. Therefore, the CCM block is commonly used for the stack and other critical OS data, this partitioning, allows the core to continue executing code while for example, a DMA transfer takes place. However, the CCM could also be used as an extra memory block, doing so is easy, and there are a few examples out there that show how, simply defining a section in the linker script will do:
.ccm : {
  . = ALIGN(4);
  _sccm = .;
  *(.ccm)
  . = ALIGN(4);      
  _eccm = .;
}>CCM

And a section attribute is used to allocate memory into that section :
const int8_t my_array[13] __attribute__ ((section (".ccm")))= {....};

However, what if you want to load initialized data into that section ? some look-up tables for example?  using that section is not enough, see, the linker script makes the distinction between the Load Memory Address  (LMA) where data is stored initially, and the Virtual Memory Address (VMA) where the data should be loaded at runtime, if the LMA is not specified explicitly, it becomes the same as VMA.

You can see here that GDB loads the .ccm data into the CCM block (LMA=VMA=0x10000000) directly, while all other sections are loaded into the flash region (0x8xxxxxx):

Loading section .ccm, size 0x4ebc lma 0x10000000
Loading section .isr_vector, size 0x188 lma 0x8000000
Loading section .text, size 0x9744 lma 0x8000188
Loading section .ARM, size 0x8 lma 0x80098cc
Loading section .init_array, size 0x8 lma 0x80098d4
Loading section .fini_array, size 0x4 lma 0x80098dc
Loading section .data, size 0xa30 lma 0x80098e0
Loading section .jcr, size 0x4 lma 0x800a310

While this may sound right, it's not, if GDB loads the .ccm section is loaded into SRAM directly, it will disappear after a power cycle! So instead, we want the LMA to be somewhere in the FLASH region (0x8xxxxxxx) and the VMA to be (0x10000000):
_eidata = (_sidata + SIZEOF(.data) + SIZEOF(.jcr));
.ccm : AT ( _sidata + SIZEOF(.data) + SIZEOF(.jcr))
{
  . = ALIGN(4);
  _sccm = .;
  *(.ccm)
  . = ALIGN(4);      
  _eccm = .;
}>CCM

Note the .jcr is included in by some startup code for something related to Java, without adding the SIZEOF(.jcr) the .ccm will overlap that section, also note the _eidata symbol which will be referenced later in code. Now, when you try to load the elf, GDB prints:

Loading section .isr_vector, size 0x188 lma 0x8000000
Loading section .text, size 0x9794 lma 0x8000188
Loading section .ARM, size 0x8 lma 0x800991c
Loading section .init_array, size 0x8 lma 0x8009924
Loading section .fini_array, size 0x4 lma 0x800992c
Loading section .data, size 0xa30 lma 0x8009930
Loading section .jcr, size 0x4 lma 0x800a360
Loading section .ccm, size 0x4ebc lma 0x800a364

Great, now the .ccm data is loaded into the FLASH region, we just need something to load it from FLASH to CCM in runtime, if you look at the startup code, there's an assembly function that copies initialized data from the flash to where it should be loaded in SRAM (the VMA), you need to do the same for the .ccm data, by either modifying the startup code, or perferrably, copying the data with a C function, so here it is:
void load_ccm_section () __attribute__ ((section (".init")));
void load_ccm_section (){
    extern char _eidata, _sccm, _eccm;

    char *src = &_eidata;
    char *dst = &_sccm;
    while (dst < &_eccm) {
        *dst++ = *src++;
    }
}
Note that the function is placed into the .init section so it executes before main. Now in runtime, this function will load the data from FLASH into SRAM using the pointer defined in the linker script.
Read more ...

Thursday, November 28, 2013

STM32F4xx Libraries



I wrote a tutorial before on how to setup a toolchain and build the STM32F4xx standard peripheral drivers into one convenient library, since then, a few people have asked me about the library, so to make life easier, I downloaded the latest StdPeriph/CMSIS, in addition to a few other libraries that I might need later, and shared everything in one repository, which currently has the following libraries:
Cortex-M  CMSIS      V3.20
STM32F4xx CMSIS      V1.3.0
STM32F4xx StdPeriph  V1.3.0
STM32_USB_Device     V1.1.0
STM32_USB_OTG        V2.1.0
In addition to those, the repository also includes a simple USB device library  (stm32f4xx/USB_Generic) which abstracts all the horrible details of the USB libraries into a very simple generic USB device implementation with just two Bulk endpoints...

To use this library you just pass a struct with two callback functions and the library will call those functions whenever data is received or requested, it's as simple as that, note that it's configured for OTG FS only, it could still be useful if you just want to get USB working and don't have time to go through all the examples.

Finally, repository also includes some examples, a Blinky, a USB_Generic example and some user-space code with libusb.

Building The Libraries:
To build the libraries and examples just type make in the top directory, the top Makefile will pass along all the flags and variables, here are some options you can pass on the command line:

make DEBUG=0
This will build everything with -O2 and no debugging symbols (not recommended)

make DEBUG=1 CFLAGS="-DOSC=xx"
This will build the library with debugging enabled, no optimization and using the given crystal frequency in MHz (for example -DOSC=16)

Repository:
https://github.com/iabdalkader/stm32f4xx.git
Read more ...

Sunday, November 17, 2013

FT231X Breakout

This is a breakout board for FTDI's latest USB-to-Serial bridge, the FT231X. This one comes in a smaller package (SSOP20) and it's cheaper than its predecessor the FT232R/L, it also offers a charging detection feature, which I'm not really interested in, but anyway see this post for more details.


I've seen a couple of good breakout boards out there, but this one has a few advantages over the others,  it has a solder jumper to switch VCCIO between 3.3V and 5.0V, a 500mA PTC fuse for over-current protection and it's pin compatible with the Arduino mini programming header.

Repo:
https://github.com/iabdalkader/ft231x-breakout.git

Read more ...

Sunday, November 10, 2013

Color Tracking With OpenMV

So I finally had some free time to work on OpenMV, for those of you who haven't been following this project, OpenMV is an open-source tiny machine vision module based on an STM32F4 ARM Cortex-M4 micro and an OV9650 sensor. I started this project mainly because I find the existing cameras are either too limited for their price or too expensive if they do some image processing, so one of my main goals was to make this as cheap as possible, the total cost of this module so far is around $20 for a single board, and could go as low as $15 for 500 pieces.

I wrote a simple color tracking algorithm for the camera, which I tested using an Arduino, the Arduino sends out a few commands via the serial port to the camera telling it to capture and process a frame, it then receives back the coordinates of the object and controls the servos accordingly. I was able to process around 15FPS, which is not bad given the current naive implementation. This is a video of the camera tracking a ball:

You can find the code and schematics here in a single repository, keep in mind that I'm still working on it, and I'm also considering a new revision to fix some minor issues and add an SPI flash for storage. If you have any suggestions/feedback please feel free to leave a comment. 
hg clone https://code.google.com/p/openmv-camera/
Update: I've created a new repo on github, this has the most recent version:
git clone https://github.com/iabdalkader/openmv.git
Read more ...

Thursday, October 17, 2013

OpenMV Update

Another quick update on my project OpenMV. I've finally managed to get the sensor working in QQVGA/RGB565 mode:


I'm using the discovery board as a debugger and a smart LCD to display the frames via USART. I've also implemented a simple color tracking algorithm, as a proof of concept:


I'm currently cleaning up the code, and I will share it with the schematics next time.. Thanks for all your support :)

Read more ...

Monday, September 16, 2013

OpenMV Camera Module

This a quick update on my camera project (OpenMV)... I've finally received the long overdue PCBs today and assembled one:


I haven't written any code yet, but I've managed to get it into DFU mode and upload a blinky, it seems to be working fine so far, no smoke :) I will post another update or a video as soon as I get something cool running.


Read more ...

Friday, July 19, 2013

NHD-C12832 Breakout

This is a breakout board for NewHaven's NHD-C12832 graphic display, a 128 x 32 pixels display with an SPI interface. I like this display mainly because it's cheap (about $11) I think it was the cheapest one I could find with this resolution, and it also looks great. However, it has an unusual package (tight pitch pins and four holes, two for the backlight and two for the screen) so I had to spend some time working on the footprint and PCB, but the end result was good.

I placed all components on the backside of the PCB to keep it as small as possible, the board has a 3.3v 150mA LDO regulator (the display operates from 2.6v to 3.3v) and a level shifter (74VHC541) to convert the logic signals to the operating voltage, so it's compatible with 5.0v logic and can be powered from 3.3v up to the maximum rating of the voltage regulator. The backlight is connected to the regulator via a MOSFET (it draws 45mA maximum) which can be controlled with PWM. The display has an SPI interface and draws about 0.45mA maximum.
The display controller is supported by u8glib, so I wrote small Arduino sketch to test drawing a bitmap,  to generate the bitmap, I used gimp to convert the image to black and white (1-bit) and then exported it to hex (save as .xbm) and then included that as a header in the sketch...



Sources:
The repository includes the Eagle files and the Arduino sketch.

hg clone https://code.google.com/p/nhd-c12832-breakout
Read more ...

Tuesday, July 9, 2013

In Search of a Better Serial Camera Module

So I've been looking everywhere for a cheap serial camera to use in my projects, preferably with some basic image processing, like object or motion detection etc.. The cheapest one I could find that barely meets my needs is sold on adafruit for $35, it has a 640x480 pixels sensor and can do some motion detection but nothing more. Then there is the more expensive modules which cost around $40 that do nothing at all and finally there's the CMUcam, which has some really nice features, but way too big and expensive (costs $100) for my needs...

So I decided to make my own serial camera, keeping in mind the basic set of features that I want:
  • Low cost
  • Small form
  • Basic image processing
  • Open source (duh!)
First, I had to choose an image sensor to use, I was inclined to use the TCM8230MD, which I'm familiar with, however, the sensor alone costs $10 and I can't seem to find it any where else other than sparkfun. So, I've decided to try the Omnivision sensors, the cheapest one I could find is the OV9650 (1280x1024 pixels) sold on ebay for $2... The nice thing about this sensors is that it connects to the board with an FPC cable (that flexible yellow cable), which means it's possible to replace it later with another one (assuming it has the same pinout) and it also has a higher resolution than the TCM8230MD. The downside with this particular sensor is that it doesn't have JPEG compression, but I could live with RGB/RAW output, after all I plan to use it mainly for image processing, or I could try to implement the JPEG compression on the micro.

Moving on to the microcontroller, a powerful micro is needed to interface with this sensor, preferably with a DCMI hardware interface, I implemented a DCMI before in software with an LPC1768/TCM8230MD and it could barely keep up, so I decided to go with something faster. 

Fortunately, I had a couple of STM32F4 micros laying around, which seemed perfect for the job since it  runs at 168MHz, has a hardware DCMI (should make it a lot easier to interface the camera) and as an added bonus, it has a floating point unit and vector processing (SIMD), making it perfect for image processing... Unfortunately, the DCMI only comes with the LQFP-100 package, so I couldn't use a smaller one. 

I started working on the PCB, first, I made a footprint for the sensor and its connector, which seems to fit nicely:
And then I moved to the layout, however, shortly after that, I realized that it's impossible to fit the sensor and micro (let alone the debugging header and interface) on a 2 layer PCB, which is what I had in mind initially to reduce the costs. So a 4 layer PCB seemed inevitable If I wanted to make it as small as possible, there's also some inherit benefits to the extra layers such as better power planes and decoupling, easier routing etc... Anyway, the first version of the PCB (25x37mm) costs around $5


The board has a triple output LDO 3.3v/2.5v/1.5v (the one I had at hand came in a QFN package) and a micro USB connector, which can be used to power the board or update the firmware with DFU. The  SWD pins are broken out for debugging (I'm currently working on a JTAG debugger too) I also throw in an RGB led (not sure if it's too close to the sensor to be visible or not)

The STM32F4 micro costs $11.79 per one, and $7.31 per 500, this adds up to around $20 for one piece and could go as low as $15 for 500 pieces,  it's much higher than I expected, but It should make up for it with some cool image processing, and still almost $15 cheaper than the adafruit camera :)

I still haven't received the PCBs yet, will post an update when I do and when I get it working I will release all the sources. I'm also giving away one for free, leave a comment if you're interested :)
Read more ...

Sunday, May 5, 2013

Running OLinuXino-MAXI on Battery


Finally I've had some time to play with my new Olimex iMX233-OLinuXino-MAXI board, the board is similar to the Raspberry pi, almost the same size and cost, however, this one has an ARM iMX233 running at 454Mhz, less RAM and no GPU.

I played with the board for a while then I decided to test it using batteries, I found out that the USB/Ethernet physical is disabled when running on batteries ! After some digging around in the datasheet, there seems to be a way around this, by swapping two jumpers (3.3V_E and 3.3VIO_E) located near the reset button that control which DC-DC converter is used, the two possible configurations for those jumpers are:
  1.  External DC-DC: 3.3V_E closed (soldered), 3.3VIO_E open (unsoldered/cut)
  2.  On-chip DC-DC: 3.3V_E open (unsoldered/cut), 3.3VIO_E closed (soldered)

Note that the datasheet mentions that the maximum current that can safely be drawn from the on-chip convertor is 200ma and you need to make sure that you don't draw more than that, I'm not sure how exactly, but you should probably use one USB device at a time and either the USB or LAN.

It also mentions that the internal DC-DC makes the chip heat a little bit, so you may want to place a small heat sink on the processor.
Read more ...

Monday, September 24, 2012

Routing Differential Signals

Differential Signalling uses a pair of complementary signals to cary data, that is each wire is carrying the opposite signal, those signals are subtracted at the receiving end and the result is either 0 for noise or 1 for a valid signal. This technique is used with high speed signals to reduce crosstalk and EMI, examples of differential signalling include the twisted pairs inside Ethernet cables, HDMI and USB.
When routing differential signals, each pair should have the exact same length, because the signals are subtracted from each other so they need to arrive at the exact same time, otherwise it's useless, the same requirement applies to other high-speed non-deferential signals such as the signals of this DRAM, note the wiggly tracks on the PCB which are used to make the tracks of equal length:

Eagle 6 has some facilities to help with differential routing, if you use an older version you could still do it manually. For Eagle 6, first give both signals the same name with one ending with _N and the other with _P, so for example USB_N and USB_P, now when you start routing either one of the signals they both will be routed together as you can see: 

If you can't route both signals together, if there's not enough space, then one will be shorter than the other, and that's when you will need the wiggly traces, or formally the Meander function. After you finish routing the signals as usual, run the meander function with the length you wish to add to the shorter trace, then click on the trace and move the mouse it will start adding wiggles to the trace:

You can also use the length.ulp to find out the difference between the tracks before using the meander function:
run length USB*
Read more ...

Saturday, September 1, 2012

STM32F4 Discovery Quick Start Guide

I finally got my hands on an STM32F4 Discovery board, those are super cheap STM32F407 ARM Cortex-M4 boards from ST. The Cortex-M4 is perfect for DSP applications as it has SIMD and an FPU and it also runs at 168Mhz. As for the board, it seems okay given its price, I really hate the headers though and it only has a few components namely, an audio DAC, a chip microphone, an accelerometer and a few LEDs.


There's also an STLINK debugger on board, which means you don't need anything else to program and debug the chip. This is a quick tutorial on how to setup a toolchain and the necessary software.

Setting up a toolchain
First thing you need to do is build or install a toolchain, I couldn't get myself to use any of the toolchains/IDEs that work with the board, as they are all propriety and they all have some sort of limitations on the free editions.

There's always the CodeSourcry toolchain, while it works fine, however, it was not built with hard-float enabled only soft and softfp, which means you have a choice between slow FP and really slow FP emulation. I also tried the summon-arm-toolchain, but it seems to have the same problem no hard-float...

I then accidentally stumbled upon a gcc toolchain which seems to be maintained by ARM and it supports soft, softfp and hard-float, I think I will be using this toolchain for every ARM Cortex I have from now on, anyway, now that you have a working toolchain you can start compiling programs but you still need drivers.

Building the drivers library:
ST provides a package that includes drivers for all the peripherals, a DSP library, API documentation and lots of examples, if you look at the examples you will see that you have to copy all the *.c files you need to your project directory along with the linker script, system initialization and startup code, personally, I like to build a monolithic library and just link with that, so you can skip this step if you want:

First download and extract the STM32F4 DSP and standard peripherals Library then copy the startup and initialization code to the src directory:
$ cp Libraries/CMSIS/Device/ST/STM32F4xx/Source/Templates/system_stm32f4xx.c Libraries/STM32F4xx_StdPeriph_Driver/src/ 
$ cp Libraries/CMSIS/Device/ST/STM32F4xx/Source/Templates/TrueSTUDIO/startup_stm32f4xx.s Libraries/STM32F4xx_StdPeriph_Driver/src/
Before you build the library, note that most of the drivers use a macro called assert_param, this macro is defined in stm32fxx_conf.h when you build a project you can enable/disable assertions, but since we're compiling this into a library the macro has to be seen at compile time, otherwise the compiler will just assume it's an external symbol and you'll get undefined references later, so you need to add this macro to the stm32f4xx header
#Libraries/CMSIS/Device/ST/STM32F4xx/Include/stm32f4xx.h
#ifdef  USE_FULL_ASSERT
  #define assert_param(expr) ((expr) ? (void)0 : assert_failed((uint8_t *)__FILE__, __LINE__))
  void assert_failed(uint8_t* file, uint32_t line);
#else
  #define assert_param(expr) ((void)0)
#endif /* USE_FULL_ASSERT */
if you #define USE_FULL_ASSERT it will enable assertions or you can compile two libraries one for normal use and the other for debugging.

Finally, copy this Makefile into the src directory and compile the library, I'm assuming here that you have the new toolchain in the path:
#Libraries/STM32F4xx_StdPeriph_Driver/src/Makefile
LIB     =  libcm4.a 
SRCS    = $(wildcard *.c) 
LIB_OBJS= $(SRCS:.c=.o)
AFLAGS  = -mcpu=cortex-m4 -mthumb -mthumb-interwork -mlittle-endian -mfloat-abi=hard -mfpu=fpv4-sp-d16 
CFLAGS  = -mcpu=cortex-m4 -mthumb -mthumb-interwork -mlittle-endian -mfloat-abi=hard -mfpu=fpv4-sp-d16 -O2 \
-I../inc -I../../CMSIS/Include/ -I../../CMSIS/Device/ST/STM32F4xx/Include/

CC = arm-none-eabi-gcc
AS = arm-none-eabi-as
LD = arm-none-eabi-ld
AR = arm-none-eabi-ar

all:: $(LIB)

$(LIB): $(LIB_OBJS)
    $(AR) -r $(LIB) $(LIB_OBJS)
    echo $(LIB_OBJ)

clean:
    $(RM) *.o *.a

.c.o :
    $(CC) $(CFLAGS) -c $<

.s.o :
    $(AS) $(AFLAGS) $< -o $@
When it's done, copy all the headers (including the CMSIS headers) and the library to somewhere like /opt or /usr/local. There's just one last piece of the puzzle missing, the linker script, you can find one in the many templates included with the library or use the one here, it also includes a Makefile template.

Blinky... Well not exactly!
To keep this simple, this example just lights up one of the LEDs on the board

#include "stm32f4xx_rcc.h"
#include "stm32f4xx_gpio.h"
GPIO_InitTypeDef  GPIO_InitStructure;
int main(void)
{
    /* GPIOG Periph clock enable */
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD, ENABLE);

    /* Configure PD12 in output mode */
    GPIO_InitStructure.GPIO_Pin   = GPIO_Pin_12;
    GPIO_InitStructure.GPIO_Mode  = GPIO_Mode_OUT;
    GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
    GPIO_InitStructure.GPIO_PuPd  = GPIO_PuPd_NOPULL;
    GPIO_Init(GPIOD, &GPIO_InitStructure);

    /* Set PD12 high */
    GPIO_SetBits(GPIOD, GPIO_Pin_12);

    /* Do nothing */
    while (1) {
    }
}
Programming and debugging
There's no "official" stlink utility for Linux, so I used this one instead:
$ git clone https://github.com/texane/stlink.git
$ cd stlink
$ ./autogen.sh
$ ./configure
$ make
This will build two binaries, the st-util a gdb server, and st-flash which is supposed to let you write the binary to flash but it doesn't really work! anyway, the project includes a udev rules, you should use that instead of sudo each time:
$ cp 49-stlinkv2.rules /etc/udev/rules.d/
$ udevadm control --reload-rules

Now just run st-util and in another terminal run gdb:
$ arm-none-eabi-gdb blinky.elf
$ tar ext :4242
$ load
$ continue

Notes
Take care not to remap the USB pins used by the STLINK debugger, if you do so the debugger won't be able to talk to the chip and you could actually brick the board :) if you do find yourself in this situation, pull the BOOT0 pin high, there's a VDD pin right next to it so just place a jumper on those pins, when you do that, the board will run the bootloader instead and you can erase the entire flash.

The library is configured for a 25MHz oscillator and the Discovery board has an 8MHz oscillator, you will need to change two values to fix that, the HSE_VALUE in stm32f4xx.h set that to (8000000) and the PLL_M in system_stm32f4xx.c to (8).
Read more ...

Wednesday, July 11, 2012

Portable SDR with Olinuxino for Tracking Wildlife

I was working on a project for a biologist friend of mine, that involved tracking RF tag implants on wildlife, using an SDR DVB-T dongle. He wanted a portable solution to be placed near the sprainting places of Otters(Lutra lutra), the main subject of the study, where they regularly come to deposit scent marks.

An RF tag is implanted on the animal which sends pulses on a frequency unique for each tag, this way we're able to tell them apart, this is what a cheap RF tag looks like,  this one has a frequency of 148.354Mhz
Software defined radio (SDR) became a bit more accessible recently, when a kernel hacker discovered that DVB-T dongles based on the RTL2832U chip can be used as a cheap SDR, since the chip allows transferring the raw samples to the host. Since the project was on a tight budget that seemed like a perfect solution...

The osmocom project provides a user space driver for the dongle, I started with pyrtlsdr, a Python binding for librtlsdr, and pylab for signal processing of the samples collected by the SDR, to compute and plot the PSD, that last spike corresponds to the signal of the RF tag above:

Finally, I ported everything to an olinuxino ARM-based board running Linux, a script runs on boot and logs the detected frequencies to file on SD card for later processing, the board still hasn't been tested in the field yet, I'm still working out some issues with the power management.
Read more ...