EEVblog Electronics Community Forum

Electronics => Microcontrollers => Topic started by: dannyf on August 13, 2014, 12:08:07 am

Title: STM32, ghetto style
Post by: dannyf on August 13, 2014, 12:08:07 am
Every once in a while, we will have discussions on what a "minimalist mcu system" looks like.

There are plenty of us who have done truly minimalist 8-bit systems. So I thought I would post a few pictures of a "minimalist" STM32 system.

The mcu in question is a STM32F030F4 - a tssop20 16k CM0 chip from STM - < 40 cents a piece, if you can get one. I got mine from China for ~60 cents.

Here are two pictures of the STM32 chip flipping an led.

Title: Re: STM32, ghetto style
Post by: dannyf on August 13, 2014, 12:10:19 am
The only part on the board, aside from the led, is the STM32 mcu. Nothing else.

No capacitors, no crystal, nothing.

The programmer? It is a knock-off st-link on a stick (like a usb thumb drive). There are everywhere on the bay for $5 dollars.

Title: Re: STM32, ghetto style
Post by: dannyf on August 13, 2014, 12:11:39 am
Wiring?

Four wires from the programmer to the chip: Vcc (3.3v), GND, SWDCLK and SWDIO.

You will see one extra wire - for BOOT0. That's only needed because the board has no connection for BOOT0, and we also want to make a even more ghetto version of this, :)
Title: Re: STM32, ghetto style
Post by: dannyf on August 13, 2014, 12:13:26 am
Next?

We will try to even get rid of the knock-off ST-link. Instead, we are going to utilize the bootloader already on the chip and do a zero cost programming exercise (assuming  you have a usb-ttl adapter).

stay tuned.
Title: Re: STM32, ghetto style
Post by: dannyf on August 13, 2014, 01:10:28 am
Development environment:

tried successfully on CoIDE and Keil.

CoIDE: I used an earlier version that has no direct support for the ST chip. So I compiled it to a generic CM0 chip. With the st standard peripheral libraries, the code size is 1.1k - 1.7k, depending on compiler settings;

Keil: with microlib and cross-modulation optimization turned on, I got 1.0k - 1.6k. However, gcc is much faster in compilation time.
Title: Re: STM32, ghetto style
Post by: westfw on August 13, 2014, 06:32:57 am
Thanks for the example / proof-of-concept.

Quote
the code to flip the led is fairly generic
At the level of the code you showed, it better be!  The question is "how ridiculous" is the chip_init() part, and the library functions (if any) under your PIN_xxx macros? (those are your macros (that you've mentioned in other threads), rather than STLib or CMSIS functions, right?)   At 1.1k, your binary is very nearly exactly the same size as the Arduino BLINK example (for ATmega328) that does the same thing.  And a lot of people criticize the arduino libraries for being bloated.
(Now, frankly, 1K for init and vectors and stuff seems OK to me, on a $0.60 16k chip...)

Title: Re: STM32, ghetto style
Post by: Psi on August 13, 2014, 06:41:27 am
Development environment:

tried successfully on CoIDE and Keil.

CoIDE: I used an earlier version that has no direct support for the ST chip. So I compiled it to a generic CM0 chip. With the st standard peripheral libraries, the code size is 1.1k - 1.7k, depending on compiler settings;

Keil: with microlib and cross-modulation optimization turned on, I got 1.0k - 1.6k. However, gcc is much faster in compilation time.

EmBlocks is another one that works well for stm32
Title: Re: STM32, ghetto style
Post by: dannyf on August 13, 2014, 11:41:17 am
In case you are interested, current consumption @ 8Mhz HSI, without the led, is just shy of 10ma. Slightly worse than a typical 8-bit mcu at comparable frequency.
Title: Re: STM32, ghetto style
Post by: andyturk on August 13, 2014, 01:11:57 pm
Keil: with microlib and cross-modulation optimization turned on, I got 1.0k - 1.6k. However, gcc is much faster in compilation time.
Even 1k seems like a lot to blink an LED. Of course, maybe 1k is the smallest size that the tool will report.
Title: Re: STM32, ghetto style
Post by: mikerj on August 13, 2014, 05:15:22 pm
Keil: with microlib and cross-modulation optimization turned on, I got 1.0k - 1.6k. However, gcc is much faster in compilation time.
Even 1k seems like a lot to blink an LED. Of course, maybe 1k is the smallest size that the tool will report.

A fair chunk of that will be interrupt vectors (forty odd 32 bit vectors), the C runtime and initialization code.  It seems like a lot compared to e.g. a PIC, but with great power comes great(er) overheads.
Title: Re: STM32, ghetto style
Post by: dannyf on August 13, 2014, 06:30:34 pm
St-link knock-off: just search for st-link v2 on the bay and the one I got has metal casing. Should be around $5 shipping included. They are of fairly high quality, with laser itched letters on them and a bi-color led indicator (red + blue).

Soldering tssop20 parts: very easy. I applied some flux on the board and then lined the chip. Applied a little bit of solder on one color and check the part again for alignment - this is the more important part. After that, just put a big drop of solder on the tip and drag it across the pins. Wipe off excessive amount and check for short. A 30 second job if you do it right.

Code size varies on settings / compilers used. Here is one example: 1.2k for the overhead (start-up, clock mgmt, and SystemCoreClockUpdate() - itself a 200b monster). PIN_OUT() is 200b; Others are 40 bytes or so.

On the most aggressive setting, you can shrink the overhead to about 500 bytes.
Title: Re: STM32, ghetto style
Post by: dannyf on August 13, 2014, 06:35:04 pm
One more.

ST pheripheral library: I used an ancient one, version 1.0.1, :). The latest one is 1.3.1. I have not tested any thing under 1.3.1. However, it should work.
Title: Re: STM32, ghetto style
Post by: SirNick on August 13, 2014, 06:46:30 pm
No decoupling cap?  No series resistors?  For shaaaame.  Think of the children...
Title: Re: STM32, ghetto style
Post by: miguelvp on August 13, 2014, 09:00:01 pm
PSoC 4200 with 28 pin SSOP is a bit more expensive at $1 for the chip alone but with a good regulated external supply it can run as is.

Quote
Regulated External Supply

In this mode, the PSoC 4200 is powered by an external power
supply that must be within the range of 1.71 to 1.89 V (1.8 ±5%);
note that this range needs to include power supply ripple too. In
this mode, VCCD, VDDA, and VDDD pins are all shorted
together and bypassed. The internal regulator is disabled in
firmware.

But not only you get a 32bit MCU, but programmable digital and analog blocks, ADC, DAC, capacitive sensing 32K of flash ram 4K rom, well tons more.

But if you use 3 decoupling caps then you can power form unregulated 1.8 to 5.5V. So a coin battery will do.
Oh, and free shipping while they still have the $1 offer, (of course it does sound like it's been subsidized or something)
Title: Re: STM32, ghetto style
Post by: djacobow on August 13, 2014, 09:01:39 pm
This is preposterous! The raw power of the 32b ARM cannot be harnessed with a mere soldering iron, a TSSOP adapter board, and a few wires!

 ;)
Title: Re: STM32, ghetto style
Post by: dannyf on August 13, 2014, 10:20:39 pm
Quote
The programmer... are everywhere on the bay for $5 dollars.

For those of us who are too cheap to spare $5 (I am one of them), there is an approach that requires zero / no (incremental) cost to program those STM32 chips: your discovery boards. They have a debugger on board and can be made as programmer for those chips.

Note: you have to provide external power, however.


Title: Re: STM32, ghetto style
Post by: dannyf on August 13, 2014, 10:29:02 pm
Another cheapie, in keeping with the ghetto style of this thread, is to use a serial port (tx/rx pins) and to activate the bootloader in the system memory of those chips.

With this approach, all you need are two wires (tx/rx) + Vcc/Gnd (and BOOT0 for this particular board), and you can program the chip.

Practically, you will be hard pressed to find a modern computer with a serial port so the practical solution is to use a usb/ttl board (232 or cp210x or pl2303) to simulate the serial board.

Here is my implementation (the pictures show the code running - thus the BOOT0 line is floating).

Four wires to the STM32 (Vcc, Gnd, TX, RX), BOOT0 floating.

In the programming mode, BOOT0 is tied to nRST - you will need to read the datasheet to understand why, :)

Title: Re: STM32, ghetto style
Post by: dannyf on August 13, 2014, 10:42:34 pm
The above approach requires a serial port (either directly or via a usb/ttl converter), and a piece of software (flash loader demonstrator, freely available from ST).

There is also an approach that does not require the flash loader demonstrator - hyperterminal is all you need.

However, you will need to adapt and program a piece of firmware (available freely from ST) and burn it to your chip (either with a programmer or via the flash loader demonstrator). After the initial programming, all you need is a serial port + hyperterminal.
Title: Re: STM32, ghetto style
Post by: dannyf on August 13, 2014, 10:43:40 pm
Hopefully, this thread will show people how easy it is to start using those arm chips, from a programming perspective.

Hope it helps.
Title: Re: STM32, ghetto style
Post by: Whales on August 13, 2014, 10:48:12 pm
I'm loving this.  I have to try them out :D
Title: Re: STM32, ghetto style
Post by: dannyf on August 13, 2014, 11:06:12 pm
Each approach has its own pros / cons:

1) st-link: it provides the most comprehensive view of the registers, and the ability to halt the processor. However, in cases of large data flow, it is not efficient;

2) serial port: it allows an efficient way to observe large number of data - you can simply program your code to utilize the uartx module to send data over the tx/rx lines. ie. the programming and user application are one. However, you have no way of halting the mcu and if you want to output a new variable, you have to reprogram the chip or program the flexibility to output variables on the fly - via the hyperterminal.

I prefer the st-link approach myself.
Title: Re: STM32, ghetto style
Post by: dannyf on August 13, 2014, 11:08:48 pm
BTW, for those of you interested, the above approaches apply to STM8S/L/A chips too - they are ST's 8-bit chips.

The STM8 chips are incredibly inexpensive - I have a few of them on a boat from China at 30 cents apiece (STM8S003F). Very difficult to beat at those price points.

Enjoy.
Title: Re: STM32, ghetto style
Post by: dannyf on August 13, 2014, 11:44:26 pm
Quote
I'm loving this.

I am glad that you find it helpful.

I have always heard people talking about how difficult and expensive it is to acquire skills and equipment to get started on those ARM chips. Hopefully this thread will demonstrate how easy and low-cost it is to get it going, at least for those STM chips.

At this low of a price point, it is a shame that more people aren't trying out those chips.
Title: Re: STM32, ghetto style
Post by: westfw on August 14, 2014, 01:02:50 am
Quote
it is a shame that more people aren't trying out those chips.

Where did you say you could purchase them from, again?  :-)

(This history of hobbyist microcontrollers is that they had to be pretty cheap, and they had to be "available" to hobbyists.  Microchip owes a lot of thanks to Parallax for their dominance in the hobbyist market. (and in the other direction, Atmel's early flash microcontrollers were nearly unobtainable.)
This assumes that the manufacturer considers hobbyist involvement to be a good thing; but I observe that in the absence of the rare "evaluation mission", a working engineer is similar to a hobbyist...
(and I'm constantly amazed at how many "eval boards" are nearly indistinguishable from, say, Arduino in terms of capabilities, but languished largely unnoticed for some reason that is really hard to put your finger on.  How are those STM "Nucleo" boards doing, anyway?))
Title: Re: STM32, ghetto style
Post by: dannyf on August 14, 2014, 01:20:07 am
Digging through my boxes and here we go, an open frame stlink/v2 knock off + a stm8s003f board.

Again a picture of it blinking the green led. The st-link is in the background and the stm8s003f board in the foreground.

Code?

The code is identical to the one posted earlier (plus some timer interrupt related stuff to calibrate the software delay routines used), also driven by the st peripheral library.

Total code size: 3.2k. Of which, about 1K is totally unrelated to blinky. 0.5K is truly blinky related and the rest is overhead.

Title: Re: STM32, ghetto style
Post by: andyturk on August 14, 2014, 02:21:34 am
The STM8 chips are incredibly inexpensive - I have a few of them on a boat from China at 30 cents apiece (STM8S003F). Very difficult to beat at those price points.
How about a Cortex M0 with 8k flash and 2k SRAM (http://www.cypress.com/?mpn=CY8C4013SXI-400) for the same price?
Title: Re: STM32, ghetto style
Post by: Kjelt on August 14, 2014, 08:38:16 am
Biggest problem with the STM8 is the compiler. Cosmic has a 1 yr 32kB free license (sponsored by ST while it lasts) or a 8kB for indefinitly.
Some other compiler farmers also have those small free compiler try outs but nothing substantial.
Title: Re: STM32, ghetto style
Post by: mikerj on August 14, 2014, 09:14:12 am
Biggest problem with the STM8 is the compiler. Cosmic has a 1 yr 32kB free license (sponsored by ST while it lasts) or a 8kB for indefinitly.
Some other compiler farmers also have those small free compiler try outs but nothing substantial.

SDCC supports the STM8, though I don't know what the code generation is like.  The STM8 tends to be overlooked because of the very low price of ARM Cortex parts, but it's a surprisingly fast micro for an 8 bitter.
Title: Re: STM32, ghetto style
Post by: Kjelt on August 14, 2014, 09:32:53 am
The STM8 tends to be overlooked because of the very low price of ARM Cortex parts, but it's a surprisingly fast micro for an 8 bitter.
In present time anno 2014 I agree, probably would also choose the Arm now, but the STM8 is out since 2008 when there were no equally cheap Arm micros.
A minus point of the STM8 I find is the lack of registers, it has only three registers and the compilers used only two of them in the beginning. Also the difference in the memorymap, it has a zero page of 128 bytes RAM that is directly addressable, the other RAM is indirectly addessable, so as a programmer you really must choose the variables you place in the zeropage wisely.
Probably the ARM M0 will take over the 8 bit domain, esp. with companies that already develop for ARM M3/4.
Title: Re: STM32, ghetto style
Post by: dannyf on August 14, 2014, 10:53:06 am
Quote
Biggest problem with the STM8 is the compiler.

True. SDCC offers limited support. I use IAR but even the limited 8K version should be sufficient for a lot of simple tasks.

Its timing is also quite unfortunate.

Quote
Probably the ARM M0 will take over the 8 bit domain,

Agreed.
Title: Re: STM32, ghetto style
Post by: dannyf on August 16, 2014, 05:48:58 pm
Here is a STM8L151F3 being debugged by the knock-off stlink - so you see what the stlink looks like in case you are interested.

The user code is identical to those for STM32F030 and STM8S003. Compiled code size on the STM8L is about 300b larger, due to the clock management stuff.

Current consumption is 1.8ma @ 8Mhz, vs. STM8S003's 10ma @ 8Mhz. Very respectable.


Title: Re: STM32, ghetto style
Post by: paulie on August 18, 2014, 01:22:09 am
This is preposterous! The raw power of the 32b ARM cannot be harnessed with a mere soldering iron, a TSSOP adapter board, and a few wires!

Actually this approach can result in practical application not just science project. Here's the original "ghetto" thread that may have been an inspiration: http://www.rcgroups.com/forums/showthread.php?t=2222027 (http://www.rcgroups.com/forums/showthread.php?t=2222027) . An stm32f103 board is built for a dollar and change which can replace a $50 multicopter flight controller when used with a cheap chinese IMU board. Links are provided for Ebay parts.

Title: Re: STM32, ghetto style
Post by: SirNick on August 19, 2014, 07:30:26 pm
Here's what I don't get, personally:  You can hack that nasty mess together, or you can spend like $8 to have OSH Park mail you a PCB of the same size, with your custom layout on it.  Certainly the difference between a $1 dev board and an $8 dev board is not make-or-break territory, is it?  A circuit that does anything interesting is going to double the cost anyway, at the very least.

I realize some people like to save every last cent / quid / gil, and others just want to do something with the parts they have in a junk drawer.  That's fair.  Different strokes and all that.  There's something to be said for being industrious enough to get a working circuit out of a scrap heap.  An actual thing you'll use more than once (like a flight controller) is a whole other ball of wax though.  I'm getting to where I debate whether to bother with a breadboard or just order a prototype PCB now.  (That might be because I often don't recover the breadboard from its original test circuit though.)
Title: Re: STM32, ghetto style
Post by: paulie on August 19, 2014, 08:51:57 pm
An actual thing you'll use more than once (like a flight controller) is a whole other ball of wax though.

As part of the recommendation to start out with an of- the-shelf controller:

Quote
if youre a rank beginner its a good idea to pick up one of these [bona fide originals]. but if experienced or like me have lots of frames and motors kicking around its nice to be able to crank out a half dozen of the cheap tricks for the same price.

It might make sense if we are talking about just one unit. But I've built several of these and have saved hundreds of dollars. Significant if Wifey keeps her eye on your "play" budget like mine does. I suspect the majority browsing here also do so from a hobby viewpoint.
Title: Re: STM32, ghetto style
Post by: Ribster on August 19, 2014, 10:28:25 pm
Here's what I don't get, personally:  You can hack that nasty mess together, or you can spend like $8 to have OSH Park mail you a PCB of the same size, with your custom layout on it.  Certainly the difference between a $1 dev board and an $8 dev board is not make-or-break territory, is it?  A circuit that does anything interesting is going to double the cost anyway, at the very least.

I realize some people like to save every last cent / quid / gil, and others just want to do something with the parts they have in a junk drawer.  That's fair.  Different strokes and all that.  There's something to be said for being industrious enough to get a working circuit out of a scrap heap.  An actual thing you'll use more than once (like a flight controller) is a whole other ball of wax though.  I'm getting to where I debate whether to bother with a breadboard or just order a prototype PCB now.  (That might be because I often don't recover the breadboard from its original test circuit though.)

SirNick, i don't think you get the point. I agree with you about the best thing to do when you're serious about a project. It doesn't cost that much money and effort to fab a board.
The cheapness, ease of use and time to blinky of this project is terrific for a beginner. And that's the target audience i think.
dannyf can tackle very complex projects, but chooses to pick this one to lower the bar for beginners.
Hell, a 1$ micro, USB->UART chip and you're up and running. That's very nice for a beginner that just wants to play and get to know the ARM world.
Title: Re: STM32, ghetto style
Post by: SirNick on August 19, 2014, 11:44:05 pm
SirNick, i don't think you get the point.

That seems to be the case. ;)

For comparison, I just whipped these up -- an LPC 81x breakout board with room for ISP and reset pull-ups, plus proper decoupling; and a TTL-to-RS-232 adapter.  The boards and serial parts cost about the same as a TTL serial cable (which I have as well.)  You would have to buy something like that to communicate with a bare MCU anyway.  The Intersil IC and supporting components costs about the same as a MAX232 in DIP alone.

Anyway, not trying to spoil the fun.  I'm all for doing it for the sake of it.  It's just that small prototype PCBs are so cheap now.  ;)
Title: Re: STM32, ghetto style
Post by: Ribster on August 20, 2014, 12:39:54 am
SirNick, i don't think you get the point.

That seems to be the case. ;)

Not trying to be the asshole here, was maybe a bit harsher then i intended ;).
But you know what i'm saying..
Nice breakouts btw.
For beginners, everything is new. Starting pcb design with eagle and ordering a pcb is sometimes a whole new world opening..
So yea, so great that you can just download some gerbers, send it to the fab and get onto learning ARM.
Should sell these on tindie ;)
Title: Re: STM32, ghetto style
Post by: westfw on August 20, 2014, 09:34:29 am
Some "beginners" don't feel that a project is "real" unless they build it themselves, and have despaired of using ARM chips because they're so "complex and difficult to deal with."  For them, this thread is especially valuable because it's an existence proof that ARMs need not be all that complicated after all.

Other beginners would be a lot better off spending $20-30 and getting a plug&play board like a Launchpad.

The people who seem determined to do things themselves, but clearly don't have the needed background knowledge ("can you build me a bootloader with XXX?  I don't know how to run "make"") drive me a little bit crazy...
Title: Re: STM32, ghetto style
Post by: dannyf on August 20, 2014, 10:37:36 am
Another ST mcu that doesn't have an unique ID is STM32F030F, per its datasheet.

Or does it?

Here is a memory dump from 0x1FFF F7A0. Notice the 12 bytes from 0x1FFF F7AC, highlighted in red? That's the unique ID, :)

If you move over to 0x1FFF F7CC (highlighted in green), you will notice 0x10 (= decimal 16) - that's the flash size in KB.

Again, since those features are "undocumented", use them at your own risk.

Title: Re: STM32, ghetto style
Post by: dannyf on August 20, 2014, 10:38:42 am
There are quite a few of such "undocumented" features, like EEPROM over 128/256 bytes, or flash size (103 vs. 207).

You can find them all if you experiment with those little devices.
Title: Re: STM32, ghetto style
Post by: dannyf on August 20, 2014, 10:46:39 am
Quote
Should sell these on tindie

It has surprised me that no one has attempted to do that: get a pcb that has minimal parts, like decoupling caps, or space for a crystal, a swd header, and put it in dip format.

Parts for maybe a dollar and fully manufactured for $2. You can probably sell it for 3 - 5 dollars + postage and make some money.

With the price of those chips + programmer, and its features, it should do well. Plus, if you put an entire ecosystem together, with an arduino like library, you get those liberal arts types interested and wola, you become an Arduino killer, :)
Title: Re: STM32, ghetto style
Post by: Kjelt on August 20, 2014, 11:26:51 am
There are quite a few of such "undocumented" features,............, or flash size (103 vs. 207).
Maybe I misunderstand but ST provides the exact flash and RAM size for each specific device?
For instance below the difference between a 103ZC with 256kB flash and 48kB RAM and 103ZD with 384kB flash and 64kB RAM?
Title: Re: STM32, ghetto style
Post by: dannyf on August 20, 2014, 11:39:30 am
Quote
ST provides the exact flash and RAM size for each specific device?

I am not sure what ST's strategy is, but you can write / read beyond the specified memory size and still be OK. This could be a strategy (it is cheaper to make just one chip and sell them as different chips at different price points), or it could be QC issues (chips that fail above 32K marked as 32K version and chiphs that fail above 16k marked as 16k version, etc.).

For example, You can try to write / read beyond the specified EEPROM / flash memory limits for your chips and see what happens.
Title: Re: STM32, ghetto style
Post by: Kjelt on August 20, 2014, 12:08:49 pm
Ah ok , see what you mean.
Well for ST my guess is definitely: strategy.
You can see that in their Arm32 portfolio (number of chips with different rom/ram sizes) you see they cover with some series the entire playingfield (32k to 1MB) and even till some extent keep the package the same!
Where for example NXP has huge gaps (need bigger ROM you get a different larger package and sometimes even a different core).

What surprises me is that they do not restrict access to those parts, with the STM8 this is not possible to my knowledge, the fuses that configure the final choice are made together with the unique id in the factory just before marking.
Title: Re: STM32, ghetto style
Post by: SirNick on August 20, 2014, 07:42:04 pm
Not trying to be the asshole here, was maybe a bit harsher then i intended ;). But you know what i'm saying..

You weren't, and I agreed with you, so no offense taken.  Likewise, I wasn't trying to be critical of the thread itself -- I'm actually really happy someone is taking the time to bring these chips down to the lay-people.  There's a documentation gap in the ARM micro ecosystem, so we need more of this.

Other beginners would be a lot better off spending $20-30 and getting a plug&play board like a Launchpad.

Yeah for sure...  However I think the default dev-board platform contributes to the stigma of complexity.  For one, the Start Here docs tend to pummel you with vendor baggage -- the JTAG and debug parts, recommended IDE, vendor's support site stuffed with more literature than you could possibly read with a year off work and a warehouse full of bran muffins...  Then there's the dev board itself -- essentially a small product of its own, with a random combo of stuff you'll use and some you won't.  Furthermore, they're geared for B2B, working engineers, and selling their unique features.

By contrast, the minimal concept is good -- it illustrates exactly what is essential, and everything else is added to that.  :-+  This thread, and stuff like it, go a long way to introducing new users, who can then ascertain what they need to study depending on what they want to do next.

Nice breakouts btw. ... Should sell these on tindie ;)
It has surprised me that no one has attempted to do that: get a pcb that has minimal parts, like decoupling caps, or space for a crystal, a swd header, and put it in dip format.

I totally agree, however I imagine it would take a while to build a personal fortune on $1-a-board profits  ;), so instead I'm working on contributing some stuff like this to the community.  I bought (another) domain and some cheap web hosting for that purpose.  (There are plenty of forums and stuff already, but I need a stable home for content.)  Working on some PHP infrastructure now, then I need to collect info, test a few PCB designs, and write some guides.  For hardware, a buy-this-PCB link to OSH Park's user contributed store thingy would make it painless to provide easy access to the parts, without having to insert myself into the distribution chain.

The TTL breakout module is designed with this in mind already.  I made it for a BeagleBone Black, with the Logic Supply case that has a DB-9 break-out tab, but it would work in a cable shell too.  The PCB is designed to mount directly to the DB-9, and can be flipped depending on whether you want the device to be DCE or DTE (it only really needs to flip TX/RX and provide a ground pin on both sides).  The Intersil IC even has an Inactive pin that's HIGH when there's a link detected, and LOW when there's not.  That lights an LED on the right side of the header, which makes troubleshooting easy.  Way more than I need, but I thought a few extra features would make it a more useful board for others.

Alright, I'm hijacking this thread now, so ... back to Mr. F.
Title: Re: STM32, ghetto style
Post by: dannyf on August 20, 2014, 08:19:29 pm
Quote
with the STM8 this is not possible to my knowledge

I don't know if that's the case. I will experiment when I get some time.
Title: Re: STM32, ghetto style
Post by: dannyf on August 20, 2014, 10:10:43 pm
So we now know that we can at least write through 0x40EF (240 bytes) but fail at 0x40FF (256 bytes)

But we want to push the boundary further and see how many writes we can take between 0x40EF and 0x40FF.

Now, we start to increment the write at 0x01 rather than 0x10.

ie., we are going to write 0xf1 at 0x40f0, 0xf2 at 0x40f1, ...., and 0x00 at 0x40ff.

Here is the memory dump, with relevant cells highlighted in green.

As you can see, we can at least push to 0x40FE. That is, stm8s003F has at least 255 bytes of eeprom, vs. 128 bytes as specified in the datasheet.

Due to data type restrictions, we don't know if we have succeeded in writing to 0x40FF -> we will figure that out later.
Title: Re: STM32, ghetto style
Post by: dannyf on August 21, 2014, 12:43:42 am
Quote
It has surprised me that no one has attempted to do that: get a pcb that has minimal parts, like decoupling caps, or space for a crystal, a swd header, and put it in dip format.

Looks like someone beat me to it: there are quite a few such boards on ebay - stm8s003f, voltage regulator, reset switch, isp header, a couple leds and 0.1" dip pin out, plus unfitted crystal.

All for less than $2 shipped. and seems to be fairly popular.

Now, all you need is some kind of arduino-like library and you are off to a great start.
Title: Re: STM32, ghetto style
Post by: neslekkim on August 21, 2014, 08:18:05 am
Looks like someone beat me to it: there are quite a few such boards on ebay - stm8s003f, voltage regulator, reset switch, isp header, a couple leds and 0.1" dip pin out, plus unfitted crystal.

All for less than $2 shipped. and seems to be fairly popular.

Now, all you need is some kind of arduino-like library and you are off to a great start.

Yeah, like these? http://www.ebay.com/itm/171346510522 (http://www.ebay.com/itm/171346510522)
$3 for two, not bad.
Title: Re: STM32, ghetto style
Post by: Kjelt on August 21, 2014, 10:57:04 am
If you analyze the cost vs profit it is rediculous:
STM $0,40 (in huge quantities)
Capacitors  $0,05
Diodes     $0,03
USB conn  $0,20
header  $0,05
switch $0,05

Total cost without pcb + manufacturing $0,78
Asking price incl shipping $1,50

Let's say they want 15% profit so price would be $1,28

So you have then $0,50 for making a gold plated PCB + manufacturing + envelope + handlingfee + shipping.

No western company can do this  |O
Title: Re: STM32, ghetto style
Post by: dannyf on August 21, 2014, 11:19:44 am
Quote
$3 for two, not bad.

It is almost criminal not to get some at those prices, :)

A STM32F030F board would be even better.

Quote
No western company can do this

Maybe if we mandate higher minimum wages, more regulation, .....

Title: Re: STM32, ghetto style
Post by: neslekkim on August 21, 2014, 07:53:45 pm
Ordered that,  a couple stm32f103 boards and the stlink clone
Will be interesting to test

Sent from my SM-T520 using Tapatalk

Title: Re: STM32, ghetto style
Post by: dannyf on August 21, 2014, 08:43:12 pm
If you need help with wiring, please let me know.

I just received 5 STM8S003F chips: at $0.30/each, it is hard to go wrong, :)
Title: Re: STM32, ghetto style
Post by: neslekkim on August 22, 2014, 09:06:33 am
I bought these exact items
stm8 board:
http://www.ebay.com/itm/171346510522 (http://www.ebay.com/itm/171346510522)
stlink clone:
http://www.ebay.com/itm/131072534999 (http://www.ebay.com/itm/131072534999)
two different stm32 boards:
http://www.ebay.com/itm/261472191025 (http://www.ebay.com/itm/261472191025)
http://www.ebay.com/itm/171275016235 (http://www.ebay.com/itm/171275016235)

Could have bought some loose chips and soldered on an adapter pcb, but the prices on these was cheap, and they have crystal, and I guess decoupling caps and everything is ok.
Not the same stm32 as you mentioned earlier, but I guess there is not that big difference on those?
Title: Re: STM32, ghetto style
Post by: dannyf on August 22, 2014, 11:00:03 am
It should be identical: swd for stm32 and swim for stm8.
Title: Re: STM32, ghetto style
Post by: neslekkim on August 22, 2014, 12:19:43 pm
yeah, meant the chip itself: STM32F030F4 vs STM32F103C8T6
Title: Re: STM32, ghetto style
Post by: dannyf on August 22, 2014, 04:40:32 pm
There are some hardware differences between the two but non in regards to debugging.

I am not sure how familiar you are with the chips / tools, but it helps if you try out some of those tools and get yourself comfortable with them. Software side of the things will be the biggest challenge early on in the process.
Title: Re: STM32, ghetto style
Post by: dannyf on August 22, 2014, 05:21:20 pm
Quote
Software side of the things will be the biggest challenge early on in the process.

On that front, I thought I would post a quick software tutorial so that people can get started quickly, again ghetto style, :)

I have been asked if I could post my complete projects used earlier in this thread. My projects utilize tons of middleware so it is quite "bloated" - a blinky for example takes over 2 minutes to compile on a dual quad-Xeon (3.0+ghz), 12GB machine, for example.

Instead, in line with the ghetto spirit, I would post 1 single file that can be compiled under CoIDE to blink an led - that would greatly simplify your life.

The code posted will be code in such a way that if you wish, can be split into multiple modules for future uses.

First of all, pre-requisites:

1) you have CoIDE installed. I am running 1.7.4, with updated components. You can download the latest one and install.
2) you have gcc-arm installed. I am running an old version (4.6 or 4.7 I think). I think the latest is 4.8 but I never bothered to try it.

Once CoIDE is installed and gcc-arm linked in (you only need to do this once), you are ready to go.
Title: Re: STM32, ghetto style
Post by: dannyf on August 22, 2014, 05:28:19 pm
At this point, CoIDE has included a minimalist main.c for you.

Code: [Select]

int main(void)
{

    while(1)
    {
    }
}

You can compile and link this main.c and a hex file will be created for download. Obviously, it does nothing.

Title: Re: STM32, ghetto style
Post by: dannyf on August 22, 2014, 05:57:10 pm
3. compile

Hit compile or build, and you will get something like this in the console:

Code: [Select]
Program Size:
      text    data     bss     dec     hex filename
      1684      20       4    1708     6ac f0 getto.elf

BUILD SUCCESSFUL
Total time: 6 seconds

indicating that the build is successful, obviously.

Title: Re: STM32, ghetto style
Post by: dannyf on August 22, 2014, 06:09:18 pm
4.1 debug - step through:

once you are in the debug mode, you have a new set of controls to explore, highlighted in red on the upper left corner.

The source code that is to be executed is highlighted in light green, by a yellow arrow, in the middle of the screen.

You can explore a bunch of things but here, we just wanted to see F_CPU (aka SystemCoreClock, a global variable). Right click in the "Variables" window on the lower right corner of the screen, you pick SystemCoreClock to display. As you step through the code, you will see how its value changed from 48000000(hz) to 8000000(hz).

Title: Re: STM32, ghetto style
Post by: dannyf on August 22, 2014, 06:29:22 pm
The code will run on other compilers as well, with minimum modifications.

Once you have mastered CoIDE / Eclipse, it is an easy transition to other IDEs: Keil  / IAR for example are considerably simpler to navigate.
Title: Re: STM32, ghetto style
Post by: SirNick on August 22, 2014, 07:11:11 pm
Not bad, sir.  :clap:

Side question:  You used the symbol 'F_CPU'... I had always assumed that was Atmel lingo.  Are you using it here because it's familiar to you (and probably many others), or is that more prevalent than I thought?
Title: Re: STM32, ghetto style
Post by: Laurynas on August 22, 2014, 09:24:42 pm
Great stuff!
Maybe you'll do a "hello world"/blinky with software steps for stm8 as well? :)
Title: Re: STM32, ghetto style
Post by: dannyf on August 22, 2014, 10:12:16 pm
8) set up the environment:

Under "C/C++ Compiler->Preprocessor", fill in the settings.

The items highlighted in red will need to change if your library folder locations are different or your chips are different.
Title: Re: STM32, ghetto style
Post by: dannyf on August 22, 2014, 10:18:58 pm
10) Comile / build:

at this point, you are ready to build your project. It should compile flawlessly.

After that, click the "Download and debug" button - highlighted in red below.

Title: Re: STM32, ghetto style
Post by: dannyf on August 22, 2014, 10:21:44 pm
11) debugging:

Now, your stlink should have downloaded the code to your chip and the execution is halted on the first line of your main() - highlighted in green by EWSTM.

Your then can explore all the nice features of the IDE + debugger + chip.


Hope it helps.
Title: Re: STM32, ghetto style
Post by: dannyf on August 22, 2014, 10:24:13 pm
STM8 is really a nice family of chips that offer tremendous amount of performance and at incredible prices. Vs. the traditional 8-bitters, the hardware debugger is really valuable in getting your code to work.

It is a shame that more people aren't using them.
Title: Re: STM32, ghetto style
Post by: dannyf on August 22, 2014, 10:31:58 pm
Code: [Select]
void chip_init(void) {
//SystemCoreClockHSI_2MHz(); //set clock to hsi, _2MHz, _4MHz, _8MHz, _16MHz
//CLK->PCKENR1=CLK->PCKENR2=0x00; //optional - disable all peripheral clocks
}

Two things about this little piece:

1) I commented out SystemCoreClockHSI_2Mhz(). It and its siblings allow you to set up the chip to run off different oscillators and at different speeds. You may wish to implement them later on. When you do, make sure that those routines update SystemCoreClock appropriately. So the delay routines will run correctly.

2) The PCKENR1/R2 registers default to turn on all peripherals -> like in PIC or AVR. Turning them off here (uncomment that line) will give you current consumption closer to STM8L chips - that may be important for battery-powered applications. You will then need to pipe clock to a peripheral before you use it. Look to stm8s_clk.h/.c files for help there.
Title: Re: STM32, ghetto style
Post by: diyaudio on August 22, 2014, 11:07:04 pm
11) debugging:

Now, your stlink should have downloaded the code to your chip and the execution is halted on the first line of your main() - highlighted in green by EWSTM.

Your then can explore all the nice features of the IDE + debugger + chip.


Hope it helps.

Great explanation. ta!
Title: Re: STM32, ghetto style
Post by: neslekkim on August 23, 2014, 10:00:57 am
Fantastic!, thanks for this explanation.
Title: Re: STM32, ghetto style
Post by: dannyf on August 23, 2014, 01:55:39 pm
It was pointed out to me, rightfully so, that the use of a commercial IDE (EWSTM) isn't exactly "ghetto".

I picked IAR because of its user friendliness and my familiarity with it. If you are comfortable with other compilers / IDEs (STVD, IDEA, etc.), feel free to use them - as the code is written heavily on the ST library, its compiler dependence is minimum - for example, for the piece I posted earlier, I compiled it successfully on Cosmic / STVD, without any modification.

The detailed steps of setting up a project is obviously IDE / compiler specific but they follow the same principle.
Title: Re: STM32, ghetto style
Post by: Kjelt on August 23, 2014, 02:27:31 pm
It was pointed out to me, rightfully so, that the use of a commercial IDE (EWSTM) isn't exactly "ghetto".
Baaah, the IAR STM8 version is free of charge till 8kB so what is cheaper then free exactly ?  ;)
Alternative would be the STVD environment downloadable free of charge from ST and the free Cosmic STM8 compiler (also 8kB limit). Install the compiler first then STVD and in the menu:
Project
project settings
Tab Genera
Toolset choose STM8 Cosmicl
Root path: \Program Files (x86)\COSMIC\CXSTM8 if not already done automatically
include path: Hstm8
Library path: lib
Title: Re: STM32, ghetto style
Post by: dannyf on August 23, 2014, 04:01:25 pm
Quote
STVD

ST is very much like Microchip: great hardware, shitty software. STVD is so 1990s in terms of its interface and user-friendliness. It is up there with Mplab, :)

Quote
the free Cosmic STM8 compiler (also 8kB limit).

If you are going to be limited, you might as well be limited by EWSTM rather than Cosmic / STVD - IDEA is only marginally better than STVD.
Title: Re: STM32, ghetto style
Post by: Kjelt on August 23, 2014, 04:30:34 pm
ST is very much like Microchip: great hardware, shitty software. STVD is so 1990s in terms of its interface
Yeah you might be right there, I am using it when I started with the ST7's that was begin 2000's, it was great then, even the simulator worked (never worked for the STM8 but the real time debug (SWIM) interface made that not such a pain anyway).
Now they even have given up development on STVD I believe, so maybe not the first tool to choose if you start afresh. I am still a bit stuck on it since I need the 32kB free Cosmic compiler for my projects, 8k does not cut it. Can you integrate a third party compiler with EWSTM and still swim debug?
Title: Re: STM32, ghetto style
Post by: dannyf on August 23, 2014, 04:41:11 pm
I don't think it is possible.

On the flip side, you may be able to get cosmic (or sdcc) to work with other IDEs (Eclipse or CB, for example). I never tried it myself but shouldn't be that difficult.
Title: Re: STM32, ghetto style
Post by: dannyf on August 23, 2014, 08:50:23 pm
Quote
The STM8 chips are incredibly inexpensive - I have a few of them on a boat from China at 30 cents apiece (STM8S003F).

I just received them today. Solder 4 of them to a TSSOP28 adapter board, and connected to my stlink clone -> wola! LED blinked, no exception. For a 30cent mcu, not a bad deal at all.

A word of caution: STM8S003F requires an external capacitor on the Vcap pin to get it going. Without it, the mcu doesn't run and doesn't talk to stlink.

The datasheet has requirements for the capacitor but I have used 4.7n poly, .1u ceramic, up to 470u elctrolytic on loooooong wires. All worked like a charm.
Title: Re: STM32, ghetto style
Post by: Kjelt on August 23, 2014, 09:20:51 pm
On the flip side, you may be able to get cosmic (or sdcc) to work with other IDEs (Eclipse or CB, for example). I never tried it myself but shouldn't be that difficult.
To build should be possible but to debug requires a dedicated plugin interfacing the resonance rlink or stlink, never heard those existed for eclipse?
Title: Re: STM32, ghetto style
Post by: dannyf on August 23, 2014, 10:38:20 pm
Quote
never heard those existed for eclipse?

No. But I am not that close to open-source universe so it is entirely possible (and likely) that I am wrong here.
Title: Re: STM32, ghetto style
Post by: mrflibble on August 24, 2014, 11:32:31 am
Looks like someone beat me to it: there are quite a few such boards on ebay - stm8s003f, voltage regulator, reset switch, isp header, a couple leds and 0.1" dip pin out, plus unfitted crystal.

All for less than $2 shipped. and seems to be fairly popular.
Oooh, nice find. Thanks for the tip.  :-+
Title: Re: STM32, ghetto style
Post by: dannyf on August 26, 2014, 12:24:29 am
Quote
0.9ma @ 2Mhz,

From the datasheet, the current consumption is 0.84ma typical, 1.05ma max;

Quote
3.9ma @ 16Mhz.

From the datasheet, the current consumption is 3.7ma typical, 4.5ma max.
Title: Re: STM32, ghetto style
Post by: dannyf on August 26, 2014, 11:28:01 pm
Highly unscientific testing of Keil mdk vs. gcc:

I have a simple blinky - similar to the one posted above but in modular form, in a project with the st standard peripheral library + my middleware (meaning that most of the code is unused).

1) Keil mdk:

with no optimization, and no discard of unused code, the output is 13KB.
with the most aggressive optimization (plus microlib) and discard unused code, the output is 1.6KB;

2) gcc-arm:

with no optimization, the output is over 37KB -> wouldn't fit my chip (STM32F030F);
with the most aggressive optimization and discard unused code, the output is 2.1KB.

amend:

3) IAR:

with no optimization, the output is 3KB - I think it must have cut unused code;
with the most aggressive optimization and multi-file compilation, the output is 1KB.

Title: Re: STM32, ghetto style
Post by: sporadic on August 27, 2014, 05:13:49 pm
Highly unscientific testing of Keil mdk vs. gcc:

I have a simple blinky - similar to the one posted above but in modular form, in a project with the st standard peripheral library + my middleware (meaning that most of the code is unused).

1) Keil mdk:

with no optimization, and no discard of unused code, the output is 13KB.
with the most aggressive optimization (plus microlib) and discard unused code, the output is 1.6KB;

2) gcc-arm:

with no optimization, the output is over 37KB -> wouldn't fit my chip (STM32F030F);
with the most aggressive optimization and discard unused code, the output is 2.1KB.

amend:

3) IAR:

with no optimization, the output is 3KB - I think it must have cut unused code;
with the most aggressive optimization and multi-file compilation, the output is 1KB.

Nothing scientific, but was curious how Atmel's solutions fared out of the box.  Here's a quick comparison against an Atmel SAM D20E14 (Cortex M0+) using GCC and ASF in Atmel Studio 6.2 (default configs).  Just a pin toggle like you had above.  Coming from AVRs, not used to seeing such high memory usage, especially data, for such basic stuff.
Code: [Select]
Debug config:
    Program Memory Usage  :    2316 bytes  14.1 % Full
    Data Memory Usage     :    584 bytes   28.5 % Full

Release config:
    Program Memory Usage  :    2204 bytes  13.5 % Full
    Data Memory Usage     :    584 bytes   28.5 % Full

Program:
Code: [Select]
#include <asf.h>

void configure_port_pins(void) {
    struct port_config config_port_pin;
    port_get_config_defaults(&config_port_pin);
   
    config_port_pin.direction = PORT_PIN_DIR_OUTPUT;
    port_pin_set_config(PIN_PA00, &config_port_pin);
}

int main (void) {
    system_init();
    delay_init();
    configure_port_pins();
   
    while(1) {
        port_pin_toggle_output_level(PIN_PA00);
        delay_ms(100);
    }
}

Title: Re: STM32, ghetto style
Post by: dannyf on August 27, 2014, 06:20:07 pm
Quote
such high memory usage, especially data, for such basic stuff.

Not too bad. Most of that stuff is the start-up code, clock mgmt, and interrupt table.

600 bytes are little bit too high - I typically get 100 - 200 bytes. But it could have included the zero-initiated data - depending on the compiler used / setting.
Title: Re: STM32, ghetto style
Post by: westfw on August 28, 2014, 07:47:03 am
Quote
not used to seeing such high memory usage
A lot of those vendor libraries look like they were developed when the smallest chip had 64k+ of flash, so coming up with space-optimized init libraries wasn't at all important.  If you really want to use those sub-$1 8-bit replacing ARMs with 16k or less, you may end up doing something else.

For additional comparison, Arduino Due runs about 10k, Teensy 3 about 12k, and Energia (for TI CM4) to about 2.5k (!)  A pruned bare-metal Keil/microlib is down to about 300 bytes, some of which is unused code that I can't figure out how to get rid of :-(  (That includes the CM4 internally-sourced interrupt vectors and dummy ISRs (up through systick), but not the ones for "external" interrupts.)


Title: Re: STM32, ghetto style
Post by: dannyf on August 28, 2014, 10:46:53 am
I looked at a particular piece of code I have in mdk - a blinky via rtc. Here is a skinny down version of its memory allocation:

1) 44 bytes for gpio related operations;
2) 100 bytes for main();
3) 74 bytes for rtc;
4) 230 bytes of flash and 1536 bytes of ram (for stack + heap) for startup;
5) 112 bytes for stm32f0xx_gpio
6) 172 bytes for stm32f0xx_rcc
7) 492 bytes for stm32f0xx_rtc
8) 24 bytes for stm32f0xx_pwr
9) 356 bytes for system_stm32f0xx
10) 620 bytes for the various libraries linked into the code

So a basic blinky should take 230 + 356 + 112 + 172 + 44 + 100 = 1kb of flash minimum. plus 600kb of library + 1.5kb of ram.

This is fairly consistent with the numbers reported earlier.

It also suggests that 4KB of flash is probably the bare minimum, and 8KB is the practical minimum for those chips.
Title: Re: STM32, ghetto style
Post by: dgtl on August 28, 2014, 04:13:14 pm
The ST lib is exceptionally bad in code size and thus also speed.
For example, take HAL_RCC_OscConfig from STM32Cube. This is a 315-line super-function, that takes a pointer to a large struct. The struct contains a bit-mask to select which osc to configure (HSE/HSI/LSE/LSI/PLL). Then the struct contains config variables for all of the oscillators. The function checks those bits in the bitmask and splits to 5 conditional branches. As a project usually does not use all of the oscillators, the user is left with lots of dead code in the conditional paths of this function, that never get executed. In addition to that, the configuration struct contains configuration variables, that are never read. Usually this function is used with a constant input once at the beginning of the code, so depending on the input a lot of dead code could be avoided. For a compiler to clean up this mess, link-time optimization is required. Even then, the code makes it especially difficult for the compiler to find the dead code and variables and elliminate them. Why isn't this thing split to separate functions, one for each osc? It would be much better not to introduce dead code at all, not hope for some compiler magic to clean up the mess (unless you are trying to sell a specific compiler that happens to do that?). This is OK for a generic-use library, but not for a embedded system.
Another example is HAL_GPIO_WritePin and similar functions in .c files. In case the target state is constant/known (and not provided in a variable dynamically), the task to do is to write to a 32-bit register a 32-bit value. In the STM library, you get a function that takes a pointer to GPIO reg base; bit mask that may have only one bit set and boolean. It is in another object file, so the compiler can not inline and optimize it. Again, unless link-time optimization is used, the simple worst case of 4 bytes register address, 4 bytes register value (or we may even use shorter values) and some bytes to perform the write takes now one more constant and many more cycles to execute.

So, the ST libraries just waste the resources. It is quite easy for non-beginners to write your own code and save huge amounts of code space and execution time. The waste of resources is in this case not an issue of ARM cpu's or 32-bit uCs in generic but just a bad implementation of the library.
One may argue that writing your own code takes a lot more time. When adding up time learning the non-obvious APIs, time debugging some issues that those APIs cause (why does the re-configuration of sysclock source from to HSE+PLL need to magically set up periodic systick timer interrupt that was not used? did I ask it to?) and debugging the performance issues later on, it can be wise to avoid bad parts of such libs and use your own.
Title: Re: STM32, ghetto style
Post by: sporadic on August 28, 2014, 06:12:54 pm
Quote
such high memory usage, especially data, for such basic stuff.

Not too bad. Most of that stuff is the start-up code, clock mgmt, and interrupt table.

600 bytes are little bit too high - I typically get 100 - 200 bytes. But it could have included the zero-initiated data - depending on the compiler used / setting.

Quote
not used to seeing such high memory usage
A lot of those vendor libraries look like they were developed when the smallest chip had 64k+ of flash, so coming up with space-optimized init libraries wasn't at all important.  If you really want to use those sub-$1 8-bit replacing ARMs with 16k or less, you may end up doing something else.

For additional comparison, Arduino Due runs about 10k, Teensy 3 about 12k, and Energia (for TI CM4) to about 2.5k (!)  A pruned bare-metal Keil/microlib is down to about 300 bytes, some of which is unused code that I can't figure out how to get rid of :-(  (That includes the CM4 internally-sourced interrupt vectors and dummy ISRs (up through systick), but not the ones for "external" interrupts.)

Just another observation, the Xmega*E5 is available in 8k-32k FLASH / 1k-4k SRAM, whereas the D20E is 16k-256k FLASH / 2k-32k SRAM.  Each part essentially being the latest  32tqfp of their 8bit Xmega family and 32bit Cortex M0+ family (Not counting D21 which brings USB).  Peripheral wise, I'd consider the D20E as a replacement for the Xmega*D4, but that's a 44tqfp package.  Bottom line, even though they require more resources, those resources are given to you.  Appreciate all the tests you're doing.  Good things to consider when trying to choose a platform.
Title: Re: STM32, ghetto style
Post by: westfw on August 28, 2014, 10:22:18 pm
Quote
It also suggests that 4KB of flash is probably the bare minimum
Meh.  Only if you assume that there won't be improved libraries and compiler options.
Like a lot of software, these are big and bloated mostly because no one has decided that it is important to do anything otherwise.
A company that cares about the difference in price between a 4k device and a 16k device can sure-as-hell spend some time fiddling with the compiler code, or write their code in assembler.

I have "blink" for Stellaris Launchpad in 68 bytes of "obvious" ARM assembler... (Yeah, that means the vector table ONLY has the stack pointer and reset vector.  Getting one of those other non-maskable interrupts would probably be not good; perhaps as bad as the usual default infinite-loop ISR... :-))

Code: [Select]
; BLINK in ARM Assembler
; For TI Stellaris/Tiva Launchpad, with LED on PF1..3
; Aug 2014, by Bill Westfield - released to Public Domain.
;
Stack_Size      EQU     0x00000200

                AREA    STACK, NOINIT, READWRITE, ALIGN=3
Stack_Mem       SPACE   Stack_Size
__initial_sp

                PRESERVE8
                THUMB

; Vector Table Mapped to Address 0 at Reset
                AREA    RESET, DATA, READONLY
                EXPORT  __Vectors
__Vectors       DCD     __initial_sp              ; Top of Stack
                DCD     Reset_Handler             ; Reset Handler

; The program itself.
        AREA    |.text|, CODE, READONLY
newmain PROC
Reset_Handler
export Reset_Handler
ldr r0, =0x400FE108  ; Sysctl_rcgc2_r
ldr r1, [r0] ;; old val
orr r1, r1, #0x20 ;; enable PORTF clk
str r1, [r0]
nop ; Wait for PORTF to get clocked.

initf mov r1, #0xE  ;; output bits
ldr r0, =0x40025000 ;; GPIO_PORTF
str r1, [r0, #0x400] ; set bit DIR to output
str r1, [r0, #0x51c] ; DEN  enable digital IO
mov r2, #8           ; Bit 3: Green LED on Launchpad
loop ldr r1, [r0, #0x3FC] ; read DATA reg
eor r1, r2           ; complement bit
str r1, [r0, #0x3FC] ; write

mov r1, #(4*1024*1024) ;; Delay count
delay subs r1, r1, #1 ; decrement
bne delay
b loop
ENDP
  END

Title: Re: STM32, ghetto style
Post by: dannyf on August 28, 2014, 10:35:30 pm
Quote
The ST lib is exceptionally bad in code size and thus also speed.

Code size and speed may not be the priority for library developers. I would argue that readability, and reliability are probably tops there, for such a chip typically with many KBs of flash.

Quote
STM32Cube

You may want to take a look at the standard peripheral libraries instead.
Title: Re: STM32, ghetto style
Post by: Koepi on September 02, 2014, 10:32:57 am
dannyf,

Thanks for this inspiration - I ordered a few STM32f030f4 end of July and some TSSOP20-2-DIP PCBs, but wasn't too sure if that could work at all. As I want stable operations, I added a few capacitors according to the datasheet - they don't cost much, the end result is still pretty close to 1 EUR per µC board.

I built three small PCBs now which work great! :) Though I'm working with Eclipse and ST Standard Peripheral Lib, so my code looks a little bit different to yours:

Code: [Select]
#include "stm32f0xx.h"
#include <stdio.h>
#include "main.h"

void init(void) {
  GPIO_InitTypeDef GPIO_InitStructure;
  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);

  // LED: Configure PA0 and PA1 in output pushpull mode
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
  GPIO_Init(GPIOA, &GPIO_InitStructure);
}

int main (void) {
  init();

  GPIOA->BRR = GPIO_Pin_0;  // Set PA0 to GND (LED on)

  while (1) {
    GPIOA->BSRR = GPIO_Pin_1;  // Set PA1 HIGH (LED on)
    Delay(500000L);
    GPIOA->BRR = GPIO_Pin_1;  // Set PA1 to GND (LED off)
    Delay(500000L);
  }
}

void Delay(__IO uint32_t nCount) {
  while(nCount--) {
  }
}

I added two tactile switches, one for pulling nRST down to GND, and another for connecting BOOT0 with nRST. That way it's much more comfortable to flash new iterations of the code to the µC via UART/USB-to-serial.

The µCs run great with more complex code, next to dimming instead of blinking the LED I added UART output, set PLL as SysCLK source and set it to 48 MHz, use the ADC, ... even using Standard Peripheral Lib that all fits still into a 5.6kByte binary.


As I can see you managed to flash the little buggers via ST-Link. I only have two ST-Link v2 USB-sticks and ST-Link v2 via STM-Discovery-boards. But I run into the issue, that connecting the board works (with Mac/Linux toolchain), I can read out all information parameters from the µC, and even erase the flash. But then something caled "flash loader" gets uploaded to SRAM and after that I run into a timeout. Thus I can only upload code via UART for now. In Windows, the ST utils only detect the supply voltage and show unknown processor.

Did you use something "unusual"? For example, ST-Link v1? How did you manage that?
Title: Re: STM32, ghetto style
Post by: dannyf on September 02, 2014, 11:09:50 am
Quote
I built three small PCBs now which work great!

Cause for celebration!

Nice job. I made one with proper pins - machined pins but the rest with just 22awg wires, :). I use jump wires to connect it to the programmer or external circuitry.

Quote
my code looks a little bit different to yours:

My code was really meant to be broken up into multiple modules  to be integrated into a project. It was rewritten into one giant file for ease of compilation. Yours will work just fine.

Quote
Did you use something "unusual"?

I wasn't quite sure if I understood your description.

I burned the user code via two approaches:

1) uart (through ST Flash Loader Demonstrator): the connection there (via a usb-ttl converter) is RX/TX (pin 17/18 from memory), Vcc/GND, plus BOOT0 tied to nRST (on the chip). I never burned any bootloader onto the chip - the chip came with a bootloader in its system memory (ST term for rom).

2) stlink (a stlink v2 clone): the connection there is SWDIO, SWDCLK (pin 19/20 from memory), Vcc/GND, plus BOOT0 to GND. Again, all user code, no bootloader.

Hope it helps. If you can clarify your issue, I may be able to help more.
Title: Re: STM32, ghetto style
Post by: Koepi on September 02, 2014, 11:26:40 am
Thanks for the fast reply!

Sorry for not being clear about the issue in the first post already: Uploading a binary via SWD fails; everything else (uploading via UART, using periphery of the µC, ...) works like charme. Yes, the code shown in the first post works properly. No issues there. :) The lengthy, explanatory intro was meant as possible addition to enhance the minimum board.

2) stlink (a stlink v2 clone): the connection there is SWDIO, SWDCLK (pin 19/20 from memory), Vcc/GND, plus BOOT0 to GND. Again, all user code, no bootloader.

There is the difference already! I didn't pull BOOT0 to GND when trying to flash the µC via SWD. The internal pulldown of the pin should be active after start/reset anyways if I understand the datasheet correctly.
It didn't seem necessary to do, as the whole flash process works up to "flash erase". On all my board the SWD upload process fails after that, it is uploading some flash loader code to the SRAM and executes it, what obviously doesn't work as the process then times out. I already tried flashing an older firmware into the ST-Link clone (which made it work with a STM32F100-board magically, by the way.)

I will try a "hard connection to GND" via wire for BOOT0 tonight.
EDIT: Sorry, I will use a 10k resistor soldered to GND. So the buttons/switches will still work. Found some other reports that a floating BOOT0 pin may cause flash writes to fail.

It's not that it would really matter, but I'd like the small bugger to work properly "with everything" and not only with UART upload; this feels like it's broken, if you know what I mean :)
Title: Re: STM32, ghetto style
Post by: dannyf on September 02, 2014, 01:21:16 pm
The STM32F100 discovery board is a st link, I think. Yes, contrary to the claim made by ST, those little things work just fine as a regular ST Link on stm32 devices.

Quote
I will use a 10k resistor soldered to GND.

It should work. I used a jump wire, :). With a floating BOOT0, the target will not be detected by ST Link. Alternatively, you can try holding down the button while flashing it.

Once soldered to ground, however, you have to use strong pull-up to be able to run the bootloader. Connecting BOOT0 to nRST will no longer work as the weak pull-up on nRST isn't able to overcome the 10K pulldown resistor.
Title: Re: STM32, ghetto style
Post by: Koepi on September 02, 2014, 01:27:26 pm
Thanks again, dannyf!

Ok, as the space is very limited on those PCBs, I will first do the test and hold the "nRST->BOOT0" button and try SWD again.  :-+

Edit: I also made a small clip from the board "in action" (well - boring, just dimming the LED and spitting out info via UART): https://www.youtube.com/watch?v=hkWmO3jxxbs (https://www.youtube.com/watch?v=hkWmO3jxxbs)

Edit2: On the net there is the info that NRST has a 100kOhm pullup - which seems wrong. The datasheet itself (http://www.st.com/web/en/resource/technical/document/datasheet/DM00088500.pdf (http://www.st.com/web/en/resource/technical/document/datasheet/DM00088500.pdf)) says on page 58 typically 40kOhm, min 25kOhm, max 55kOhm internal pullup/pulldown for all pins, on page 62 30kOhm min, 40 typical and 50kOhm max for NRST. I will try a weaker pulldown for BOOT0, say 100kOhm or more.
Title: Re: STM32, ghetto style
Post by: bingo600 on September 02, 2014, 03:03:56 pm
I ordered 10 of the small ST's , but decided to "leave the Ghetto" , and get 10 nice PCB's for $7

http://www.aliexpress.com/item/10-pcs-Free-ship-stm32f030F4p6-system-board-learning-board-stm32-stm32f03-empty-plate/2030923590.html (http://www.aliexpress.com/item/10-pcs-Free-ship-stm32f030F4p6-system-board-learning-board-stm32-stm32f03-empty-plate/2030923590.html)

They seemed easier to populate

A finished board on ali (to expensive) , but shows component placement.
http://www.aliexpress.com/item/stm32f030F4P6-stm32-Cortex-M0-system-board-learning-board-development-board-evaluation-board/1701304725.html (http://www.aliexpress.com/item/stm32f030F4P6-stm32-Cortex-M0-system-board-learning-board-development-board-evaluation-board/1701304725.html)

Hopefully i get the stuff during the next weeks.

/Bingo
Title: Re: STM32, ghetto style
Post by: dannyf on September 02, 2014, 05:26:17 pm
Quote
I will try a weaker pulldown for BOOT0, say 100kOhm or more.

That wouldn't be able to pull the BOOT0 down to reproduce a reliable '0'. 10K is the right number if you wish to implement a pull-down. I would try pressing the button for now, :)
Title: Re: STM32, ghetto style
Post by: Koepi on September 02, 2014, 06:30:39 pm
I even dared using a weak pulldown of 250kOhm :-DD

Success!
- µC starts reliably now; before I needed to plug in power some times until the µC executed the program.
- BOOT0 switch still works for flashing via UART.
- In Windows, ST-Util from ST now detects the µC properly. I connected RST from ST-Link clone to nRST of the µC board. Flashing a .hex worked. Debugging/stepping through the program/reading registers, all works!

Unfortunately, the texane/st-link still fails flashing the program, so I'm still stuck with UART flashing. But at least it works on the µC  and seems just to be a software issue in Max OS X.

Soldered a 250kOhm pulldown to the other two boards now as well. It helps that the PCB is double sided, so it was easy to find some space.

Thanks for all those hints, dannyf. Now I'm really satisfied with the minimum DIY ARM microcontroller board  :-+
Title: Re: STM32, ghetto style
Post by: dannyf on September 02, 2014, 08:01:00 pm
Quote
Success!

A round of beers for everyone!

Quote
Unfortunately,...

If you had gotten ST-Link Utility to work, your SWD connections are good. Everything from this point onward is software, and debugging at source code level should work now.

Not knowing what "texane" is, I cannot be of much more for you.
Title: Re: STM32, ghetto style
Post by: neslekkim on September 02, 2014, 08:49:10 pm
Not knowing what "texane" is, I cannot be of much more for you.

Opensource stlink software: https://github.com/texane/stlink
Title: Re: STM32, ghetto style
Post by: dannyf on September 02, 2014, 09:50:03 pm
If so, your issues are likely with the opensource software. The hardware side (of SWD) is certainly working, as the ST-Link Utility shows.
Title: Re: STM32, ghetto style
Post by: mrflibble on September 02, 2014, 10:20:36 pm
Opensource stlink software: https://github.com/texane/stlink

Also used this in the past. These days I mostly use openocd, which has less issues in combination with ST.
Title: Re: STM32, ghetto style
Post by: dannyf on September 05, 2014, 04:53:36 pm
If it helps, I can post adc / random number generator code I used in a separate thread.

The code itself is fairly simple. But it helps if you break it down into individual modules.
Title: Re: STM32, ghetto style
Post by: Koepi on September 06, 2014, 04:28:58 am
I managed debugging in Mac OS X now. It is as simple as suggested - starting with booting into bootloader. Then st-link works in Linux/Mac as well and it is possible to step through the code, look at the variables, ...

Some more code snippets?

How about pushing the frequency from 8 to 48 MHz, and set ADC to the internal 14MHz HSI clock? :)

Code: [Select]
// ---- Setup PLL for 48 MHz :) ----
RCC_DeInit();
RCC_HSEConfig(RCC_HSE_OFF);
RCC_PLLCmd(DISABLE);
RCC_PLLConfig(RCC_PLLSource_HSI, RCC_PLLMul_12);
// Flash: 1 WaitState for 24MHz < SysCLK < 48 MHz
FLASH_SetLatency(FLASH_Latency_1);
FLASH_PrefetchBufferCmd(ENABLE);
// Set ADC clock to internal 14MHz HSI source
RCC_HSI14Cmd(ENABLE);
RCC_HSI14ADCRequestCmd(ENABLE);
// and turn the PLL back on again
RCC_PLLCmd(ENABLE);
// set PLL as system clock source
RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK);
// ---- End of Setup PLL for 48 MHz :) ----

ADC looks like this with Standard Peripheral Lib:
Code: [Select]
GPIO_InitTypeDef GPIO_InitStructure;
ADC_InitTypeDef  ADC_InitStructure;

RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE);

// ADC-init for Temperature probe
ADC_DeInit(ADC1);
ADC_InitStructure.ADC_Resolution = ADC_Resolution_12b;
ADC_InitStructure.ADC_ContinuousConvMode = DISABLE;  // on demand
ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_T1_TRGO;
ADC_InitStructure.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None;
ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;  // 12 bit right aligned
ADC_InitStructure.ADC_ScanDirection = ADC_ScanDirection_Upward;
ADC_Init(ADC1, &ADC_InitStructure);

ADC_ChannelConfig(ADC1, ADC_Channel_4, ADC_SampleTime_13_5Cycles);
ADC_DiscModeCmd(ADC1, ENABLE);
// ADC calibration; but not used as returned value ends nowhere now...
ADC_GetCalibrationFactor(ADC1);
ADC_Cmd(ADC1, ENABLE);

// Probe on PA3+4
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_4;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN;
GPIO_Init(GPIOA, &GPIO_InitStructure);

GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOA, &GPIO_InitStructure);

// end of init code ...

int readADC(void) {
uint32_t temp = 0;
GPIOA->BSRR |= (GPIO_Pin_3);  // Enable Sensor
// throw awaynfirstresult like on AVR? first value is wrong.
ADC_StartOfConversion(ADC1);
while(ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC) == RESET);

for (uint8_t i = 0; i<16; i++) {  // oversampling
ADC_StartOfConversion(ADC1);
while(ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC) == RESET);
temp += ADC_GetConversionValue(ADC1);
}
GPIOA->BRR |= (GPIO_Pin_3);  // Disable Sensor, save power
return (temp>>4);
}

I could also post a simple UART output for text feedback via terminal.

One issue remaining is that I can only use 13 IOs. Putting my LED to PF0 and PF1, adopting the code to initialize GPIOF + Clocks, ... nothing happens there. As you can see in the PLL / frequency init above, HSE is definatly disabled, in which case PF0 and PF1 should be usable as GPIO.
Maybe some voodoo is needed there. :D
Title: Re: STM32, ghetto style
Post by: bingo600 on September 06, 2014, 08:07:55 am
I got my STM32's , but not the final PCB's yet.

I hacked a ghetto style print together on a tssop-28 board , complete w. 5v to 3v ldo , caps and a dual led.

I adapted this stm32F0 repos to fit the F030
https://github.com/szczys/stm32f0-discovery-basic-template

You have to adapt the linker file to fit the F30 (16k flash /4K ram) , and adjust the initial stakpointervalue
See Device/ldscripts/stm32f0discovery_def.ld    , i have attached the modified one.

I also replaced the contents of src/main.c with the one from dannyf.


Bacically you run the following commands:

make clean
make all
make program

Or all in 1

make clean all program

And power off / on the STM32F030 board , now it blinks the led on PA0/PA1



Ohh i had to split the "reset halt" commands into separate lines or oocd would complain during programming.
in the extra/stm32f0-openocd.cfg  command file

And the oocd board definition location th the makefile.

I can't attach the full project as it is 1MB+ zipped , but I have attached the files that i modified.

/Bingo


Edit:
I have a 100K pulldown on BOOT0 (you can see it) , and there's a 560R SMD's on the led pins

Edit2:
If using OOCD like i do - Save some time and remember to adjust 
Code: [Select]
set WORKAREASIZE 0x1000 = (4K ram) In the board definition file you are using.

I (the repos linked) was using stm32f0discovery.cfg witch has 8K Ram and 
Code: [Select]
set WORKAREASIZE 0x2000,
and amazingly it worked for the test blinky , but when i switched to the current ST lib 1.3.1 it failed to program the flash every time.


Title: Re: STM32, ghetto style
Post by: Koepi on September 06, 2014, 08:59:00 am
Nice board, I like the idea with the LDO.  :D  The space on the TSSOP20-adapter is too limited for that.

I wonder why you needed to adopt the linker files. I use the generic stm32f0xx-ones which come with the Eclipse plug-ins / standard peripheral lib, they work flawless.
Title: Re: STM32, ghetto style
Post by: bingo600 on September 06, 2014, 10:04:10 am
Nice board, I like the idea with the LDO.  :D  The space on the TSSOP20-adapter is too limited for that.

I wonder why you needed to adopt the linker files. I use the generic stm32f0xx-ones which come with the Eclipse plug-ins / standard peripheral lib, they work flawless.

If you use kapton on the back side , can't you squeeze a small LDO on there , like i did ??



The author made it for the F51 (discoveryF0) that has 8K ram , and one of the exported values are the initial stak , pointing at top 8K.
My F30 was NOT HAPPY with a SP initialized to "8K" , when i only have 4K ram.

Code: [Select]
/*
Linker subscript for STM32F051 definitions with 64K Flash and 8K RAM
Copyright RAISONANCE 2007
!!! This file is automatically generated by RIDE !!!
Do not modify it, as it will be erased at every link.
You can use, copy and distribute this file freely, but without any warranty.
*/

/* Memory Spaces Definitions */

ENTRY(Reset_Handler)

MEMORY
{
  FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 16K
  RAM  (xrw) : ORIGIN = 0x20000000, LENGTH = 4K
}

/* highest address of the user mode stack */
_estack = 0x20001000;

_estack was 0x20002000; in the original ld file.


I always use makefiles , even when using Code::Blocks , and i haven't decided if i'm going to try out eclipse.

But anyways as i use makefiles and not the GUI "clicky-clicky" , i have to adapt those things for my self.

Not a problem when used to it.

But if you FSCK up' the stack , the MCU is going into "unknown orbit" somewhere , or maybe just HardFault  ;)


/Bingo
Title: Re: STM32, ghetto style
Post by: dannyf on September 06, 2014, 11:11:45 am
Quote
How about pushing the frequency from 8 to 48 MHz

I would put some wait there and then at the end update SystemCoreClock - in case you use it in the rest of the code.

Title: Re: STM32, ghetto style
Post by: dannyf on September 06, 2014, 12:31:38 pm
Quote
PF0 and PF1 should be usable as GPIO.

Forgot to mention this.

PF0/1 can be used as gpio pins only if HSE is disabled and clock is routed to it. You can disable HSE only via RCC_DeInit() or clearing the HSEON bit (bit 16).

So stepping through the code and watching the gpio registers and the RCC registers would be helpful.
Title: Re: STM32, ghetto style
Post by: Koepi on September 06, 2014, 12:54:14 pm
The HSE is disabled via deinit(), and it doesn't matter where I put the line
   RCC_HSEConfig(RCC_HSE_OFF);
- it doesn't help before or afer deinit(). I also modified CMSIS/stm32f0xx.c, there is some code for SysCLKinit where HSE gets set to on initially. That doesn't change anything. Stepping through the SystemInit with the debugger sounds reasonable. Would be the first time I find something with that ;)

@bingo600: Ah, I didn't recognize it's EM:BLOCKS, I don't use that. I also have a 051-Disco but in Eclipse with that GNU-ARM extension stuff and CMSIS, STM-Standard peripheral lib, I get to choose the processor just by M0-class.
Don't know why, but mem.ld correctly has 18kb flash and 4kb ram in it. sections.ld only has absolute values for stack size min/max. To be honest, I didn't even look at it until now as it just worked well :D

Working with makefiles is great, but I like the comfort of having an auto complete with variables/function lookup and a nice overview of all files from the project and so on. It's more like a matter of taste. (I think the projects and includes are way too complex nowerdays to control them completely "by hand", thus I prefer a click-click-GUI.)
Title: Re: STM32, ghetto style
Post by: Koepi on September 06, 2014, 02:16:25 pm
Shoot!

I must have soldered something wrong on my "main testing board". Just took another one and it works as it should.

Sorry about this fuzz. Always use a multimeter and check your soldering/connections ...
Title: Re: STM32, ghetto style
Post by: dannyf on September 06, 2014, 02:30:47 pm
That's how we all learn, :)

Quote
Always use a multimeter and check your soldering/connections

Just be a little bit cautious about that: the voltage on the +/- probes can exceed the maximum voltage those pins can take. Many times, a visual inspection (under a magnifying glass) is all it takes.
Title: Re: STM32, ghetto style
Post by: Koepi on September 06, 2014, 04:18:56 pm
Thanks for that tipp. I only measure with a "beeper" (continuity tester?) if there is a connection between the pin of the µC and the DIP-pin soldered, thus there is no current going into the µC.
As expected, PF1 had no connection - although there was plenty of solder which I needed to clean up first to produce no short.

Now it also works with my first prototype. I can only repeat again and again: This tiny bugger is just _awesome_. And so small!

Size comparison as attachment between stm32f103rb-, f103c8-, f103c8-like-leaflab-maple minimum boards, Arduino Pro Mini, Arduino Pro Micro and Arduino Nano. That tiny green thing is this board. :)
Title: Re: STM32, ghetto style
Post by: dannyf on September 06, 2014, 04:55:25 pm
You used a ssop20 board? I used a ssop28 board - so mine is slightly bigger.

Yes, it is tiny. I think NXP had some bga Cortex-M parts too that are just as big as a grain of sand.
Title: Re: STM32, ghetto style
Post by: dannyf on September 06, 2014, 05:34:12 pm
Overclocking:

STM32F030 is spec'd to 48Mhz.

With flash latency 0: it runs to 52Mhz but craps out at 56Mhz;
With flash latency 1: it runs all the way to 64Mhz.

Not bad for something that's supposed to cost 30cents each.
Title: Re: STM32, ghetto style
Post by: Koepi on September 06, 2014, 06:35:58 pm
Nice idea! Stable dimming, measuring and UART at 64 MHz:

Code: [Select]
STM32F030-Test begins.
HCLK is 64 MHz, PCLK 64 MHz, System 64 MHz, ADC 14 MHz.
Temp: ~20 degrees C.
Temp: ~23 degrees C.
Temp: ~23 degrees C.

_But_  energy consumption increases significantly. With 48MHz, it drops to 0,13W and peaks at 0,27W.
With 64 MHz, it still peaks at 0,27W, but never drops below 0,22W.

(This is in combination with CH340G usb-2-serial adapter with a power LED as well.)
Title: Re: STM32, ghetto style
Post by: dannyf on September 06, 2014, 07:06:36 pm
It is so fast that it should be criminal, :)
Title: Re: STM32, ghetto style
Post by: dannyf on September 06, 2014, 09:10:34 pm
I just noticed that CoIDE has updated its chip database to support F429/439 - no library support for those chips yet, however.
Title: Re: STM32, ghetto style
Post by: Koepi on September 07, 2014, 07:12:29 am
My parts list is still growing ...
Just read a bit about ferrite beads. Using a 10 µF capacitor next to the 100nF one is already great. Those ferrite beads are cheap in bigger volumes (100pcs SMD), so I ordered some and will use one  on the VDDA pin for the connection to VDD. Should eliminate pretty much the rest of the noise - sources on the net write about the last 10% noise which is still there after using those two capacitors - and allow for more precise ADC readouts.

I'm looking forward to play around with those 1,6x0,8mm parts ... :D
Title: Re: STM32, ghetto style
Post by: dannyf on September 07, 2014, 01:32:50 pm
Stepping through the next line, here is the output of our random number generator (32-bit):

0x077dbfbf (125681599).

Obviously, one would expect that each execution generates different numbers - hopefully, :)
Title: Re: STM32, ghetto style
Post by: dannyf on September 07, 2014, 01:34:58 pm
Stepping through the code to examine variables and registers is a great way to debug the code.

However, if you need to output massive amount of data - like to output the random numbers for a test under diehard, you would need other ways, typically a usart module. You can capture the output there and export it to a text file to be processed later.

Title: Re: STM32, ghetto style
Post by: dannyf on September 07, 2014, 01:42:43 pm
Since this thread is about someone going on the chip, we aren't going to pile on many modules here - or the code gets too out of hand.

It is a good time for you to learn to code in a modular fashion - the pieces of code posted here actually came from 4 - 5 separate modules (.h and .c files). They are co-mingled here for convenience and in a minimalist fashion.

I would encourage you to think of ways that are conducive to you to break up main.c into multiple modules. I can see a module handling clocks / chip initialization; a module handling gpio; a module handling adc1; a module handling random number generation;....

The code segments posted here are to provide the bare minimum functionality. However, they do serve to provide a basic function from which more functionality can be easily added: like set up an output in open drain; or an input with pull-up or pull-down; or the adc with scanning; or dma data transfer, etc.

The goal is so that next time, when you need those functionality, all you need is to copy those .h/.c modules to your project folder and link them into your project -> they are instantaneously available to you, and can be used with the confidence that they have been thoroughly debugged by you.

Writing a giant main.c is the surest sign of an overpaid programmer, :)
Title: Re: STM32, ghetto style
Post by: dannyf on September 07, 2014, 01:45:11 pm
You may notice that the code is written so that it can be easily broken into modules.

Take this line for example:

Code: [Select]
#define ADCx ADC1 //adc1 module used

It is expecting that when you create your adc2 module, you can simply redefine ADCx to ADC2, and other changes, and the new adc2.c will recompile flawlessly.

When you attempt to break the code into modules, think about that.
Title: Re: STM32, ghetto style
Post by: dannyf on September 07, 2014, 01:52:22 pm
Quote
typically a usart module.

Implementing a usart tx module on those chips is a breath. You need to implement three functions:

1) usart_init() to initialize the module to handle a certain baud rate, data length, stop bits, etc. It is executed once;

2) usart_puts() to transmit a string. You have two options here - use an interrupt or polling. For such a fast chip, it is a waste if it is not implemented through interrupt.

3) usart_busy() to tell if the module is busy. The trick here is to rely on the transmission buffer, not the transmission register.

Title: Re: STM32, ghetto style
Post by: dannyf on September 07, 2014, 02:50:33 pm
As the code is developed on top of the ST standard peripheral library which has fairly good cross-platform compatability, porting the code to a different chip (F1/F3/F4 for example) is fairly easy.

Title: Re: STM32, ghetto style
Post by: westfw on September 07, 2014, 10:06:34 pm
Quote
[be modular]
#define ADCx            ADC1                  //adc1 module used

It is expecting that when you create your adc2 module, you can simply redefine ADCx to ADC2, and other changes, and the new adc2.c will recompile flawlessly.
One of the annoying things about most of these 32bit chips is that a peripheral will be dependent on other registers of other peripherals that you can not easily derive, algorithmically (RCC[ADC1] |= ClkEnaBit[ADC1];) nor symbolically (RCC_ADC1 |= ADC1_CLOCKBIT;)   The clock distribution registers are the most obvious example, but also things like:
Code: [Select]
   if (GPIOx == GPIOA ) RCC_APB2PeriphResetCmd(RCC_APB2Periph_GPIOA, ENABLE);
else if (GPIOx == GPIOB) RCC_APB2PeriphResetCmd(RCC_APB2Periph_GPIOB, ENABLE);
else if (GPIOx == GPIOC) RCC_APB2PeriphResetCmd(RCC_APB2Periph_GPIOC, ENABLE);
else if (GPIOx == GPIOD) RCC_APB2PeriphResetCmd(RCC_APB2Periph_GPIOD, ENABLE);
are really ugly.  And code-bloating.  (And the ST peripheral library contains similar code, so it's not dannyf's fault.)  It wouldn't be so bad if these were set up as inline, or templates, so that the compiler would eliminate unneeded code, but that's certainly NOT the case when the code is off in the external peripheral library.)
Title: Re: STM32, ghetto style
Post by: Koepi on September 08, 2014, 06:02:50 pm
A friend of mine is electronics engineer and he showed me to "staple" the capacitors. This is quite logical as the paths are way shorter this way for the 10µF capacitor. The ferrite beads didn't arrive yet, still I wanted to correct that now already.

As I'm now playing with i2c, the pins PA9 and PA10 are used for that. Thus for flashing I need to use SWD via st-link. I put UART output via AF to PA3+PA4. And now something really weird happend: texane/st-link _works every single time_.  No need to press reset or BOOT0. It just works.  :-+
Edit: I just verified, it's the proper decoupling! Without UART connection, st-link still works!

I don't know whether the proper decoupling is to blame or the "rewired" UART. Anyhow, I'm really happy now.

The UART output module would look like this in my case, by the way:

Code: [Select]
static char text[255];

// init stuff
USART_InitTypeDef USART_InitStruct;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);

// UART1: Configure PA2 and PA3
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2 | GPIO_Pin_3;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOA, &GPIO_InitStructure);

GPIO_PinAFConfig(GPIOA, GPIO_PinSource2, GPIO_AF_1);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource3, GPIO_AF_1);

USART_InitStruct.USART_BaudRate = 57600;
USART_InitStruct.USART_WordLength = USART_WordLength_8b;
USART_InitStruct.USART_StopBits = USART_StopBits_1;
USART_InitStruct.USART_Parity = USART_Parity_No;
USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStruct.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;
USART_Init(USART1, &USART_InitStruct);
USART_Cmd(USART1, ENABLE);
// end of init


void uart_tx(char *out) {
while (*out) {
while(!(USART1->ISR & USART_FLAG_TXE)) {
// Nothing, really.;
}
USART1->TDR = *out++;
}
}

Usage example:
Code: [Select]
        RCC_ClocksTypeDef Clocks;
RCC_GetClocksFreq(&Clocks);

sprintf(text, "STM32F030-Test begins.\r\nHCLK is %d MHz, PCLK %d MHz, System %d MHz, ADC %d MHz.\n", (Clocks.HCLK_Frequency/1000000), (Clocks.PCLK_Frequency/1000000), (Clocks.SYSCLK_Frequency/1000000), (Clocks.ADCCLK_Frequency/1000000));
uart_tx(text);
Title: Re: STM32, ghetto style
Post by: dannyf on September 08, 2014, 09:24:42 pm
I would try to do uart transmission via interrupts so it doesn't tie down the mcu. If you have tons to send, DMA would be better.
Title: Re: STM32, ghetto style
Post by: dannyf on September 11, 2014, 11:47:46 pm
What doesn't STM32F030F have?

Well, it does not have TIM6, nor does it have TIM15, consistent with the datasheet.
Title: Re: STM32, ghetto style
Post by: Koepi on September 12, 2014, 04:33:01 am
My Mac OS X flash tool even suggest 64kByte of flash:
Code: [Select]
MacBook-Air:Release koepi$ ./flash.sh
stm32flash 0.3

http://stm32flash.googlecode.com/

Using Parser : Intel HEX
Serial Config: 57600 8E1
Version      : 0x31
Option 1     : 0x00
Option 2     : 0x00
Device ID    : 0x0444 (STM32F030/F031)
- RAM        : 8KiB  (4096b reserved by bootloader)
- Flash      : 64KiB (sector size: 4x1024)
- Option RAM : 12b
- System RAM : 3KiB

Wrote and verified address 0x080014f0 (100.00%) Done.

I don't know how reliable these values are, though. Some of my minimum stm32f103c8 boards are shown as having 128kByte flash, too.
Edit: Just found it in the versioning system: https://gitorious.org/stm32flash/stm32flash/commit/0255c1cf4bcc4412c4cdd1e60be35ab2aedcffa8
"The values for RAM, flash location and size etc are deducted from the chip ID and not reported explicitly by the device. They are also not always true."


On a sidenote, I "assembled" a useful table of AF pinout, find it attached.
Title: Re: STM32, ghetto style
Post by: westfw on September 12, 2014, 07:14:23 am
Quote
On a sidenote, I "assembled" a useful table
Nice.  Why can't datasheets contain such concise info.

Would you be willing to make this a shareable google spreadsheet?  Then you can re-sort on assorted columns, which I find to be useful, sometimes (I have a docs for Arduino pinouts: https://docs.google.com/spreadsheet/ccc?key=0AqdMB5dovDUZckNXSnNQa0FiWldNMFhWcHV1ODFzR0E&usp=sharing )
Title: Re: STM32, ghetto style
Post by: enz on September 12, 2014, 08:38:33 am
Quote
On a sidenote, I "assembled" a useful table
Nice.  Why can't datasheets contain such concise info.

Well, they do:

(https://www.eevblog.com/forum/index.php?action=dlattach;topic=35113.0;attach=108849;image)
Title: Re: STM32, ghetto style
Post by: dannyf on September 12, 2014, 10:40:21 am
Quote
stm32f103c8 boards are shown as having 128kByte flash

F103C8s definitely have more than 64KB of flash -> they are actually CBs?

There are also examples where non-USB STM32F were found to have USB capabilities. I think ST is marking down higher spec chips so they can occupy a wider spectrum of the market. Actually making those lower spec chips is more expensive for them.

The downside with this approach is that programmers like ST-link cannot access those "excess flash" -> unless you to the higher spec versions. Instead, you have to use IAP.

Quote
The values for RAM, flash location and size etc are deducted from the chip ID and not reported explicitly by the device. They are also not always true.

That has not been my experience -> the reported numbers are always correct.
Title: Re: STM32, ghetto style
Post by: Koepi on September 12, 2014, 10:57:21 am

Well, they do:
<kinetis datasheet screenshot>

Well, Kinetis is a different µC ;)

It's all there in the STM32F03xxx datasheet as well. But it is split up in two bigger tables, for all pinout versions, so you have to jump back and forth to combine them to your actual µC incarnation pinout.

Is there a way to put a google spreadsheet up "anonymous"? I dislike the idea of strangers sniffing in my Google account ;) I think as a single image it is already as useful as it can be, sorting around with 15 usable pins is not really necessary :D

@dannyf: That makes sense and usually is what processor manufacturers do; known from Intel since the early days, back where you could use a drill to activate the FPU of "crippled down" 486sx ( https://en.wikipedia.org/wiki/Intel_80486SX (https://en.wikipedia.org/wiki/Intel_80486SX) ). Edit: Uh, actally that was an April Fool's joke from Andreas, that hole drilling didn't turn out well ;) http://dictionary.reference.com/browse/intel+486sx (http://dictionary.reference.com/browse/intel+486sx)
Title: Re: STM32, ghetto style
Post by: dannyf on September 12, 2014, 11:08:09 am
I have a compaq laptop that uses those crippled SX chips. It is kind like today's notebook running Atom with a mono STN lcd display. It is still somewhere in the house, :)
Title: Re: STM32, ghetto style
Post by: Koepi on September 12, 2014, 11:56:01 am
Nice :) Couldn't afford a laptop back then - my first PC was a 486DX50 (yes, that wonder-thing _without_ the 25MHz x2 bus. But still with a Turbo switch :D ).

But back to topic: I wonder why your ghetto style works without problems without any additional part. Well, maybe it's just the blinking of the LED at the default 8 MHz, that doesn't put much stress on the power lines.

I now finally have:
- the stm32f030f4 µC,
- 2 100 nF block capacitors,
- 1 10µF additional block capacitor,
- 1 250kOhm pulldown resistor for BOOT0,
- 1 ferrite bead

Fading (thus fast switching noise on the power lines) the LED, using a higher frequency, using the ADC - that all sums up that you need a few more parts to make the µC work stable and properly.

Now I'm still finetuning the result. Enamelled copper wire seems to suffice as it makes no difference when I connect the VDDA with thin "normal" wire. I think an additional 1µF capacitor next to the 100nF at VDDA (as suggested by the ST AppNotes and the datasheet) may stableize the ADC even more. Though for first tests the 1-2 LSB precision is already very nice.

Title: Re: STM32, ghetto style
Post by: dannyf on September 12, 2014, 12:21:52 pm
Quote
I wonder why your ghetto style works without problems without any additional part.

Those things are pretty robust - in that regard, the STM32 isn't that unique, as I have done similar things with other chips.

Quote
Well, maybe it's just the blinking of the LED at the default 8 MHz, that doesn't put much stress on the power lines.

The fastest "blinky" I have done on this very setup is 64Mhz (1ws) and 48Mhz (0ws). zero problem whatsoever. The chip is powered via a st-link clone over a 5-6 inch wire. VDDA connected to VDD via another 5-6 inch wire. Absolutely no additional part.

The little thing just keeps going.
Title: Re: STM32, ghetto style
Post by: Koepi on September 12, 2014, 12:47:01 pm
You're right, that "just blinking" isn't too much to ask from a µC. That also works with ATtiny13/85 without 100nF block capacitor ;)

For the st-link to work properly the additional parts were necessary, and for a proper precision when measuring with the ADC. If you don't need that, it should be ok to use the µC "ghetto style". It's just that it's not reliable in all conditions (other than room temperature and mediocre air humidity, for example.) I guess.
Title: Re: STM32, ghetto style
Post by: dannyf on September 12, 2014, 01:05:05 pm
Quote
it's not reliable in all conditions

For sure. It is appropriate to do good decoupling and layout, especially for demanding applications.

The goal of going "ghetto" is to show how little it takes to get the chip running.
Title: Re: STM32, ghetto style
Post by: paulie on September 12, 2014, 01:51:26 pm
Good to see we are finally gravitating here to what is really the best choice, not only for STM, but ARM in general. No point in those STM8 which can't even begin to compete with old 8 bits like PIC and AVR. F0 no competition in terms of popularity/availability. Maybe someday, maybe never, but not at this time.

ps. Regarding 64/128k a quick peek at the RCGroups link I posted here answers that in the first posts. Those who have bothered to fire up the ST flash demo utility also find out quickly that the default 64k setting can be over-ridden on the next page and tested with "fill" functions there.
Title: Re: STM32, ghetto style
Post by: Koepi on September 12, 2014, 01:58:36 pm
Heh, those stm8 ... I saw those boards for 2 bucks for two pieces, so I ordered them. And a third one for another 3 bucks which hd some more GPIO and memory. But then the problems start: SDCC can work with Eclipse, but where to finde the equivalent of ST Standard Peripheral Lib? As the small stm8s don't have a bootloader, where is the program to upload the binary via SWIM?
I just gave up on them.

These stm32f030 are what I was looking for in terms of building my first own development board. Ok, I put a ATtiny13 SOIC8 on a DIP adapter, used a socket and some RGB LED, tactile switches and stuff for testing that out, but the way too little memory was limiting everything.

Thus cheap 32bit power, combined with my own hands, is what makes me really happy :)
Title: Re: STM32, ghetto style
Post by: dannyf on September 12, 2014, 02:20:21 pm
Quote
where to finde the equivalent of ST Standard Peripheral Lib?

st.com

Quote
As the small stm8s don't have a bootloader, where is the program to upload the binary via SWIM?

I use IAR-STM8 and the embedded programming via st-link does all the work for me. It was a breeze.

I also got it work on STVD/Cosmic through swim. Fully supports debugging and programming.

Their beauty is in the incredibly low prices - I got mine for 15 cents delivered. Tough to beat that.

I have not done much extensive testing but I think those 003s are actually 103s marked down.

They are a lot more feature limited vs. the 32F030 chips.
Title: Re: STM32, ghetto style
Post by: dannyf on September 12, 2014, 02:30:38 pm
Quote
combined with my own hands

Someone could have made an adaptor, with the chip + decoupling gaps + power connectors + pins soldered on, like they did with the 003 chips.
Title: Re: STM32, ghetto style
Post by: dannyf on September 12, 2014, 02:33:26 pm
Actually I posted a piece of the ghetto code for STM8S003 earlier in the thread. It realizes on the STM8S standard peripheral library and should work on all STM8S chips.
Title: Re: STM32, ghetto style
Post by: paulie on September 12, 2014, 02:55:55 pm
Thus cheap 32bit power, combined with my own hands, is what makes me really happy :)

I agree there is nothing more fun than DIY specially considering how cheap these things are. I also ordered both STM8 and F0 parts but only after getting hooked by the 103c. Basically out of scientific curiosity since I am one also of those geeks that likes to poke into a new chip every day.

Ok, I put a ATtiny13 SOIC8 on a DIP adapter, used a socket and some RGB LED, tactile switches and stuff for testing that out, but the way too little memory was limiting everything.py :)

Not if you shuffle off the C shackles and open yourself to asm tools. Tiny13 has proven very powerful on sites like RCGroups and Arduino forum.

Even though i'm mostly a PIC fanboy I must admit AVR is king of the mountain due to Arduino and ridiculously easy programming. AVRdude with  UASBasp or even just 4 wires to a parallel port. But more performance, memory, more IO and UARTS of these F1 chips are hard to beat. Built in boot clinches it. There's a reason this particular chip, like all the good ones, floats to the top.
Title: Re: STM32, ghetto style
Post by: dannyf on September 12, 2014, 09:41:03 pm
To continue the ghetto tradition, here is a stm32f030f running at 8Mhz on a 4Mhz crystal.

Total part count: 3 (stm32f030f, an led, a 4Mhz crystal).
Title: Re: STM32, ghetto style
Post by: westfw on September 12, 2014, 11:39:18 pm
Quote
On a sidenote, I "assembled" a useful table [of Alternate Function Register values]
Huh.  That's interesting.  I went to put together a similar table for the f103, and discovered that it apparently has a MUCH different way of configuring the "alternate functions"!

(now, does the ST peripheral library HIDE that for you, or do you end up with different initialization procedures for, say, an I2C peripheral depending on which chip you use?)
Title: Re: STM32, ghetto style
Post by: Koepi on September 12, 2014, 11:56:04 pm
There are tiny differences in the Standard Peripheral Lib setup for periphery. Among others, GPIO is different between all families, a STM32F0 setup throws compiler warnings with STM32F4.
The differences are small. You can get past them very easy by searching for example code for the µC family, for example "stm32f0 i2c example".
Title: Re: STM32, ghetto style
Post by: dannyf on September 13, 2014, 12:10:19 am
Running on an 8Mhz crystal, no PLL.

A word of warning: for crystals less than 2Mhz (or 4Mhz to be safe), you may need a parallel resistor or both load capacitors to get the oscillator starting. I guess the drive power isn't that big (to save current consumption).

Or you can put your fingers on the leads to get it going.
Title: Re: STM32, ghetto style
Post by: dannyf on September 13, 2014, 12:47:21 am
We talked about using adc to generate random bits.

Here is the STM32F030 ghetto board generating a few of those random bits.

The code is fairly simple:

Code: [Select]
  if (rand1_adc()) {PIN_FLP(LED_PORT, LED_A | LED_C);} //flip led
Title: Re: STM32, ghetto style
Post by: Kjelt on September 13, 2014, 09:31:43 pm
Concerning cheapo ebay stm32 chips/boards, just an observation, the prices are really low for the 103s with and without boards, almost impossible to beat, the chip alone from farnell is more expensive.
But then you want to step up to lets say a 207 or 217 to do some IP stack and have some more ram.
You get a shock the cheapest listings on the same china ebay stores are now more expensive then farnell. Strange is it not?
Title: Re: STM32, ghetto style
Post by: paulie on September 13, 2014, 09:58:47 pm
Maybe it's so cheap because it's the most popular ARM in the world (scale of mfg). Maybe it's most popular because it's cheap. Either way there is no competition in it's class. About time to start showing up in the "ghetto".
Title: Re: STM32, ghetto style
Post by: westfw on September 13, 2014, 11:26:26 pm
Quote
prices are really low for the 103s
Does anyone have the historical background for this chip/board?  Usually, when some board appears on eBay from all the Chinese entrepreneurs who also sell clothing and cosmetics, it's a copy of something.  (something profitable.)  For example, there are plenty of "arduino pro micro" clones, and the DIP version of this ARM board looks like a clone of the Leaflabs "Maple mini."  Sometimes they're involved in some quasi-legal hack (rooting your video game or cable box, for example.)   But I don't recall seeing this "big JTAG connector + breakout" STM32F103 board before ...
Title: Re: STM32, ghetto style
Post by: dannyf on September 13, 2014, 11:37:48 pm
Quote
the prices are really low for the 103s

Google GD32F103C8T6. Compatible down to the binaries and works with STM standard peripheral library. Less than 80 cents each in large quantity.

I suspect EBay 103's are re-masked GD chips.

Quote
But then you want to step up to lets say a 207 or 217 to do some IP stack and have some more ram.
You get a shock the cheapest listings on the same china ebay stores are now more expensive then farnell. Strange is it not?

F2s are very / fairly rare. So high prices are not unusual.
Title: Re: STM32, ghetto style
Post by: Kostas on September 14, 2014, 09:18:27 am
Concerning cheapo ebay stm32 chips/boards, just an observation, the prices are really low for the 103s with and without boards, almost impossible to beat, the chip alone from farnell is more expensive.
But then you want to step up to lets say a 207 or 217 to do some IP stack and have some more ram.
You get a shock the cheapest listings on the same china ebay stores are now more expensive then farnell. Strange is it not?

Surprisingly, it doesn't seem to be the case, at least for the STM32F207VCT6. It costs 7,84€ at Farnell, while Mouser sells them for 8,83€. The two Chinese sellers I found at Ebay sell them considerably cheaper and Aliexpress prices drop to below 5€, if you buy more than 1 ic. The two ebay sellers that were more expensive than Farnell were British and I have a strong suspicion that they just list whatever Farnell has and order - resell as needed.
Title: Re: STM32, ghetto style
Post by: dannyf on September 14, 2014, 11:09:13 am
Quote
For those of us who are too cheap to spare $5 (I am one of them), there is an approach that requires zero / no (incremental) cost to program those STM32 chips: your discovery boards. They have a debugger on board and can be made as programmer for those chips.

It cannot be true ghetto without somehow having a STM32 Discovery board in the mix, :)

Here is a picture of a STM32VL Discovery powering and programming / debugging the STM32F030F ghetto style.

Just follow 3 simple steps below:

1) Take off jumper CN3 on the discovery board -> see the green arrow numbered "1";
2) Wire Vdd (pin 16) on the ghetto board to a 3.3v pin on the Discovery Board, and wire Vss (pin 15) on the ghetto board to one of the GND pins on the Discovery Board. BOOT0 on the ghetto board is already wired to the Vss (pin 15) on the ghetto board -> see the green arrow numbered "2";
3) Wire SWCLK (pin 20) on the ghetto board to SWCLK (pin 2) of CN2 on the Discovery Board. Wire SWDIO (pin 19) on the ghetto board to SWDIO (pin 4) of CN2 on the Discovery Board -> see the green arrow number "3".

Now, sit back and relax - you are all done. The Discovery board is now a ST-Link (v1) to the ghetto board. Full programming / debugging capabilities available.

Without resorting to iap, you cannot get any more ghetto than this, :)
Title: Re: STM32, ghetto style
Post by: dannyf on September 14, 2014, 11:12:34 am
This basic approach can be used to other STM32 Discovery Boards -> most discovery boards follow the same layout / jumper set-up.

Most of those boards are very inexpensive and you probably already have them laying around. So zero incremental costs.

Title: Re: STM32, ghetto style
Post by: dannyf on September 14, 2014, 01:35:35 pm
The assembly file is coded in the most primitive way, on purpose - you will see lots of repetitions there.

You can easily replace those with macros or functions once you get up to speed. But for a minimalist approach, it works.
Title: Re: STM32, ghetto style
Post by: paulie on September 14, 2014, 01:46:48 pm
LOL
Title: Re: STM32, ghetto style
Post by: Kjelt on September 14, 2014, 02:58:52 pm
Surprisingly, it doesn't seem to be the case, at least for the STM32F207VCT6. It costs 7,84€ at Farnell, while Mouser sells them for 8,83€. The two Chinese sellers I found at Ebay sell them considerably cheaper
Well then you have a different ebay search results than I do, I came up with only one supplier for around $11 incl shipping  :palm:
To give you an idea, if you order a couple of thousand these will cost you around $2 - $3 each.
Title: Re: STM32, ghetto style
Post by: dannyf on September 14, 2014, 03:25:07 pm
Quote
for around $11 incl shipping

No clones for the STM32F2 chips, yet: the GD32 chips are F1 chips at this point.
Title: Re: STM32, ghetto style
Post by: dannyf on September 19, 2014, 02:30:04 pm
If sometimes it is desirable to use blocking transmission routines, it can be done this way:

Code: [Select]
  usart1_init(MYBAUD_RATE); //initialize the module

  while (1) {
    while (usart1_busy()) continue; //wait for the prior transmission to end
    usart1_puts(my_string);  //load up the string to be transmitted
    //while (usart1_busy()) continue; //wait for the current transmission to end.

The while state can be placed before or after the usart1_puts(). Putting it before usart1_puts() makes the transmission more efficient - you load up the string to be sent and the mcu can go do other things while the transmission is in progress.

Putting the while statement after usart1_puts() ensures that the uart module is always available when you need it.
Title: Re: STM32, ghetto style
Post by: dannyf on September 19, 2014, 02:31:41 pm
The set of usart routines utilizes usart1. But it can be modified, with minimum changes, to run on usart2 or usart3.

If you were to do that, it is best to split this into a .c/.h file so those pieces can be reused on other projects.
Title: Re: STM32, ghetto style
Post by: dannyf on September 19, 2014, 02:34:34 pm
The code is fairly straight forward. With probably one exception:

Code: [Select]
//in the ISR:
if (*_UxTX_ptr) { //0 indicates the end of the string - send null at the end
//if (*(_UxTX_ptr+1)) { //0 indicates the end of the string - don't send null at the end

As structured, the routine will send the null character at the end of a C-string. I find this useful as a way to frame a transmission.

Sometimes you don't want to send the null character - it would mess up copy-and-paste for example.

Alternatively, you can uncomment the next line, which, if activated, will NOT send the null character.

However, that means you cannot send an empty string -> ie, the first character of a string to be transmitted cannot be null.

Hope it helps.
Title: Re: STM32, ghetto style
Post by: dannyf on September 19, 2014, 09:19:17 pm
Here is one of the largest projects I have ever compiled.

ucos2 + emwin on an old keil uvision. Pictured at O0 but minimum changes at O3. Unused code already trimmed.

It is amazing what those little things can do.

And how broad the range of application is, from the ghetto chips to the CM4 (this one).
Title: Re: STM32, ghetto style
Post by: dannyf on September 20, 2014, 03:09:38 pm
Quote
F103C8s definitely have more than 64KB of flash -> they are actually CBs?

STM32F103C8 is spec'd to have 64K flash.

Reading the flash size register @ 0x1fff f7e0 shows 0x0040 -> 64K. All is good.
Title: Re: STM32, ghetto style
Post by: dannyf on September 20, 2014, 03:10:29 pm
Write 0x12345678 to flash offset 0xf000 (just shy of 64K):

all is good.
Title: Re: STM32, ghetto style
Post by: dannyf on September 20, 2014, 06:24:44 pm
"wiring?"

I used a ghetto board -> point to point connection on hook-up wires for the test STM32F103(C8). The programmer is a clone ST-link v2.

Ghetto Board              ST-link v2
=========================
BOOT0                        GND
VDD                            3.3v
GND                            GND
SWCLK                        SWCLK
SWDIO                        SWDIO


If you use a F103 board with jtag, you can use jlink on the jtag or wire the st-link v2 pins to their corresponding jtag pins -> BOOT0 is already grounded.

The only question there is if your F103 board is externally powered. If it is, do NOT connect the 3.3v line; Otherwise, you connect the 3.3v line and the st-link can power the F103 board.

I can post a picture later if that helps.
Title: Re: STM32, ghetto style
Post by: paulie on September 20, 2014, 09:17:54 pm
Aha... so looks like we finally move out of the ghetto and into the burbs. Inevitable I suppose because that crippled STM8/FO stuff was getting old. At last dannyf figures out (with a little help) where ARM is really at. Except that decrepit JTAG baloney. So looks like the 103 stuff finally came in. Better late than never. I for one would love to see some pics.
Title: Re: STM32, ghetto style
Post by: Koepi on September 21, 2014, 10:24:17 am
I checked how the tiny STM32F030 fares with its power supply, putting the probe between GND and VDDA on the soldered DIP pins. I use a small usb-2-serial adapter which also feeds the board with power. It has a small LDO aboard which spits out ~3.3V, up to ~150mA load.

https://www.youtube.com/watch?v=1_BKee138TQ (https://www.youtube.com/watch?v=1_BKee138TQ)
I had to decal the scope (as I didn't know about "AC" when testing yesterday ;) ) to see something, thus the amplitude looks less than it really is. Even with full proper decoupling (100nf+10µF VDD, 10nF+1µF VDDA+ferrite bead) according to the data sheet, there is a ripple of ~40mV. You can see the pseudo PWM for LED dimming quite clear in the scope.

Therefore the nearly stable readings from the ADC are quite amazing. :)

When trying to even that out with an additional 470µF electrolyte capacitor on GND+VDD, the "jumps" become waves. And then the ADC is getting instable, jumping around +-1 ADC value for each measurement.

I wonder how the ghetto version looks on the scope. Maybe later on I will solder a naked board, unfortunately my time is too limited to do that right away.
Title: Re: STM32, ghetto style
Post by: dannyf on September 21, 2014, 10:44:54 am
Quote
I wonder how the ghetto version looks on the scope.

Roughly in the same neighborhood.

Here is the STM32F030F ghetto board blinking an led randomly (using adc). The led is wired across two pins, without a resistor -> on current of roughly 17-20ma. No supply decoupling at all. Powered by a st link v2 clone.

The chip itself runs at 8Mhz.

The scope is ac coupled. You see the baseline ripple caused by the mcu itself, and on top of it, the randomly little bumps when the led is turned on. The ripple caused by the led is less than 1 div but more than half a div -> 10 - 20mv.

ADC fluctuates 20 - 30 digits.
Title: Re: STM32, ghetto style
Post by: Koepi on September 21, 2014, 11:58:48 am
Thank you for the graph! :)

Well, that looks a whole lot different, the decoupling is really effective then on my board - only the jumps from the current draw of the LED are visible.
My LED is sitting there ghetto-style as well, no series resistor. Thus it should take 20mA, give or take a few mA.

Maybe that is really enough, the supply has to be somewhat stable, it only mustn't jump around in very small time-slices for proper IC function.
Title: Re: STM32, ghetto style
Post by: dannyf on September 21, 2014, 12:07:39 pm
I had tried to put a 10ohm serial resistor in the supply line -> causing 200mv of ripple. I couldn't program the chip with the serial resistor in but it otherwise runs just fine, :)

As long as you don't do analog stuff, I think the ripple requirement is fairly low.
Title: Re: STM32, ghetto style
Post by: dannyf on September 21, 2014, 12:24:39 pm
Here is a shot of the supply ripple with a 0.1uf capacitor attached.

It basically eliminated the 8Mhz baseline you saw earlier. With that gone, the rippled cause by the led is super-evident.

Title: Re: STM32, ghetto style
Post by: Koepi on September 21, 2014, 01:05:49 pm
Hehe - yes, that's what I'd expect from missing decoupling: Weird effects where you wouldn't expect them, like not being able to flash the µC.  ;D I'm getting closer to understand this thing a bit better:

http://youtu.be/1NuCtXfbq4U (http://youtu.be/1NuCtXfbq4U)

Found the opportunity to build up the scope again, this time with AC coupling. Now I can perfectly monitor the power supply. I had a 100 Ohms resistor flying around, so I added it to the LED. What I can see now is a ripple of around 1mV, which seems to be quite ok or even good. And a slow voltage drop of ~12mV from the LED. That slow voltage drop doesn't seem to cause any issues with the µC's periphery, while short time ripple itself has possibly weird results, depending on the earth ray angle ;)

Thanks for the direkt comparison with and without a 100nF capacitor; this shows the big effect in practice, in a realistic scenario!
Title: Re: STM32, ghetto style
Post by: paulie on September 21, 2014, 01:19:43 pm
Hey, what's with this F0 stuff. I thought everybody here was over that. Maybe not everybody rolls up their sleeves and builds a $1 DIY but surely at least the Ebay 103 "blue boards" are starting to arrive.

Just kidding. I know some of us do enjoy playing with these oddball parts and I certainly look forward to it when mine arrive sometime in the next couple days. Back to the ghetto, here we go (went?). Haha.
Title: Re: STM32, ghetto style
Post by: dannyf on September 21, 2014, 01:53:24 pm
Quote
I'm getting closer to understand this thing a bit better:

Learning by doing, :)
Title: Re: STM32, ghetto style
Post by: dannyf on September 21, 2014, 06:17:06 pm
The little bugger that could:

Just wanted to see how far I could push the envelope.

STM32F030F (rated maximum speed of 48Mhz), ghetto board, 8Mhz crystal. 0 wait state. GCC + CoIDE.

Flipping a pin (unloaded), 50Mhz drive on the pin.

The main loop is just a bunch of pin flip instructions.

I then measured the frequency on the pin, under various PLLx settings and compiler settings (O0 and O1):

Code: [Select]
//pin frequency in Khz, Cpu frequency in Mhz.

PLLx F_CPU O0 O1
2 16 1595 3982
3 24 2393 5973
4 32 3191 7984
8 64 6383 15928
9 72 7181 17919
10 80 7979 19921
11 88 8777 21901
12 96 9575 23856

I stopped at 12x/96Mhz.

I have to say that for a chip rated at 48Mhz, costing 32 cents (official price) apiece, that's very remarkable.
Title: Re: STM32, ghetto style
Post by: dannyf on September 22, 2014, 10:23:59 am
Quote
I am still a bit stuck on it since I need the 32kB free Cosmic compiler for my projects, 8k does not cut it.

you may want to search stm8 usb on github.

Use at your own risk.
Title: Re: STM32, ghetto style
Post by: dannyf on September 22, 2014, 11:02:11 pm
A little bit more testing on wait states and their impact on performance.

Again, the same STM32F030F ghetto style, running on 8Mhz crystal, PLL'd to 96Mhz, flipping an led.

The frequency under WS0 vs. WS1:

Code: [Select]
PLLx F_CPU WS O0 O1
2 16 0 1595 3982
3 24 0 2393 5973
4 32 0 3191 7984
8 64 0 6383 15928
9 72 0 7181 17919
10 80 0 7979 19921
11 88 0 8777 21901
12 96 0 9575 23856


PLLx F_CPU WS O0 O1
2 16 1 1587 3935
3 24 1 2380 5903
4 32 1 3174 7871
8 64 1 6348 15742
9 72 1 7142 17710
10 80 1 7936 19678
11 88 1 8729 21645
12 96 1 9523 23613

The loss is about 1%.
Title: Re: STM32, ghetto style
Post by: westfw on September 22, 2014, 11:29:49 pm
I wonder how ST defines/implements a "wait state" on flash.  Even the benchmarks I did on 103 (which showed about 10% per wait-state using more pessimal code) show that it has to be something different than the full clock tick it meant back in the Z80 days.
Title: Re: STM32, ghetto style
Post by: dannyf on September 23, 2014, 12:36:44 am
Not quite the ghetto style, STM32F100RB running on WS0 and WS2:

Code: [Select]
PLLx F_CPU WS O0 O1
2 16 0 571 888
3 24 0 857 1333
4 32 0 1142 1777
6 48 0 1714 2666
8 64 0
10 80 0
11 88 0
12 96 0


PLLx F_CPU WS O0 O1
2 16 2 571 888
3 24 2 857 1333
4 32 2 1142 1777
6 48 2 1714 2666
8 64 2
10 80 2
11 88 2
12 96 2

The chip doesn't run at PLLx8 or over (64Mhz or over). But it runs fine up to 48Mhz, for a chip that's rated 24Mhz.

2x over its rated max clock rate. Not bad.
Title: Re: STM32, ghetto style
Post by: Koepi on September 23, 2014, 06:33:32 pm
The test is nice, but there is a .. but ;)

The flash latency only comes into play when there is code read from the flash. Next to a latency flag there is a flag for a cacheing mechanism. The code for flipping a pin obviously fits very nicely into this cache. I find modern techniques mentioned for the ST-µCs like branch cache, instruction prefetch and so on.
http://www.st.com/web/en/press/en/t2477 (http://www.st.com/web/en/press/en/t2477)

Thus more complex and unpredictable code flow will show the worst case performance, while pin toggling should be very close to "run from RAM" performance. Which is the case, as your tests show. :)

Calculating the first 1000 digits of Pi for let's say 1000 times and measuring the time needed would be a more suitable test for flash latency and ALU performance, I think.
Title: Re: STM32, ghetto style
Post by: Kjelt on September 23, 2014, 09:04:02 pm
The flash latency only comes into play when there is code read from the flash. Next to a latency flag there is a flag for a cacheing mechanism. The code for flipping a pin obviously fits very nicely into this cache. I find modern techniques mentioned for the ST-µCs like branch cache, instruction prefetch and so on.
http://www.st.com/web/en/press/en/t2477 (http://www.st.com/web/en/press/en/t2477)
That is for the F2 series they have a branch cache, the F1 series only has a prefetch queue.
Title: Re: STM32, ghetto style
Post by: dannyf on September 23, 2014, 09:53:47 pm
Quote
Thus more complex and unpredictable code flow will show the worst case performance,

Houston, we have a winner!

You are absolutely correct. The unbelievably good performance under WS>0 is ******entirely****** due to the predictable nature of the code -> so that they can be stored in the pipeline and flash latency settings are entirely irrelevant.

If you put entirely unpredictable code in there, there will be significant penalty for WS>0.
Title: Re: STM32, ghetto style
Post by: dannyf on September 24, 2014, 12:37:11 am
Tried the following test on my STM32F030F ghetto board.

The code tests a random number (generated from the adc module) and branches out to one of two identical routines that blink the same led.

We then measure the frequency of the LED blinking.

0WS: 360Khz;
1WS: 247Khz, or ~2/3 of the speed with 0WS.

Title: Re: STM32, ghetto style
Post by: westfw on September 24, 2014, 01:16:24 am
What about just a short loop?  Your original version had a bunch of unrolled bitflip sequences, right?
A short loop:
   while (1) { bitflip(LED); }
defeats both the internal pipeline and the flash prefetcher, I think (but would do better with a smarter "flash accelerator."  Probably.)
1/3 slower sounds more like a traditional wait state, after all, since other indications show that writing to gpio is a two-cycle operation.


Title: Re: STM32, ghetto style
Post by: neslekkim on September 24, 2014, 10:11:45 am
How long until we get an similar guide for the stm32f7? :)
Title: Re: STM32, ghetto style
Post by: dannyf on September 24, 2014, 10:52:51 am
Quote
stm32f7

If and when that chip is made, :)
Title: Re: STM32, ghetto style
Post by: Koepi on September 24, 2014, 01:08:43 pm
There you are, here it is: http://www.st.com/web/en/catalog/mmc/FM141/SC1169/SS1858 (http://www.st.com/web/en/catalog/mmc/FM141/SC1169/SS1858) ;)
http://www.st.com/web/en/catalog/mmc/FM141/SC1169/SS1858?icmp=ss1858_pron_pr-stm32f7_sep2014 (http://www.st.com/web/en/catalog/mmc/FM141/SC1169/SS1858?icmp=ss1858_pron_pr-stm32f7_sep2014) (only a few hours old)

Not yet listed at Farnell, no Cortex M7 as choice ...
http://www.newark.com/webapp/wcs/stores/servlet/Search?st=stm32&catalogId=15003&categoryId=800000028003&langId=-1&storeId=10194 (http://www.newark.com/webapp/wcs/stores/servlet/Search?st=stm32&catalogId=15003&categoryId=800000028003&langId=-1&storeId=10194)

But I fear that's nothing for ghetto style.
Title: Re: STM32, ghetto style
Post by: Kjelt on September 24, 2014, 01:35:51 pm
Interesting this Tightly-Coupled Data/Instruction Memory, any idea what that is about, is it fast mem 0WS or something like that or?????

Found it:
http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0338g/Chdhbjjb.html (http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0338g/Chdhbjjb.html)

Quote
The purpose of the Tightly-Coupled Memory (TCM) is to provide low-latency memory that the processor can use without the unpredictability that is a feature of caches.
Title: Re: STM32, ghetto style
Post by: dannyf on September 24, 2014, 03:04:37 pm
It looks more like a processor with lots of pins than a microcontroller - I guess that's where everything is going.

Quote
But I fear that's nothing for ghetto style.

It does come in LQFP packages so ghetto'g is still possible.

As it is just announced it will be months if not a year+ before it is available. It took STM32F030F quite sometime to be available in limited quantities.
Title: Re: STM32, ghetto style
Post by: dannyf on September 24, 2014, 03:12:08 pm
The likely target for the M7 chip is the proprietary 32-bit chips (Freescale / Renesas), or the dsp chips (TI).

Interestingly, Freescale is one of the three launch customers for M7. ST being one makes a lot of sense to me. Atmel being one doesn't quite - maybe the days of AVR32 are really numbered.

It will be interesting to see if ARM takes a high-performance single core or a medium performance multi-core approach for microcontrollers. NXP took the later route and wasn't terribly successful. The single core approach would bring down market many of the tools and approaches used by micro-processors in the handset market.

Time to really check out DS-5 I guess.
Title: Re: STM32, ghetto style
Post by: dannyf on September 27, 2014, 05:59:34 pm
STM8S003F, doing pwm on tim1, ch3 (PC3).

The picture on the left was taken when the led as going from fluctuating from 0->100% duty cycle.

The picture on the right was taken when the led is fixed to 1% duty cycle.

TIM1 has 4 pwm channels and TIM2 has three pwm channels.

So TIM1 configured into pwm generation + sensors + algorithm is essentially your flight controller for a quadcopter;

Do the same to TIM2 and you have a tricopter.

Coding is super easy.
Title: Re: STM32, ghetto style
Post by: paulie on September 27, 2014, 06:35:42 pm
Afraid not danny. More than a dim LED does multicopter make. PID, Kalman, waypoint sequencing, GUI interface, complementary filters, and lots more. Neither STM8 nor F0 is up to the task. Not even close. In fact 103 even overloaded to 128k is considered old school by some and pushing for F4. Me thinks you have stepped a little too far outside your area of expertise this time.
Title: Re: STM32, ghetto style
Post by: Koepi on September 27, 2014, 08:10:59 pm
paulie, I think you're looking at this from the wrong angle.

You can setup a _cheap_ working controller unit for a quad wiith a STM8 or an F0.

What you're describing is from the "development front".
And there you could say, wow, F4xx is even too small: Ask a Boing engineer what he thinks about a single F4xx ;)

dannyf didn't claim that you can build the non-plus-ultra-blowing-all-away quad; he wrote that you can build a controller for it (even if it's just a very simplistic one, without GPS, autonomous pathfinder, POV video, ...).
Title: Re: STM32, ghetto style
Post by: paulie on September 27, 2014, 08:29:28 pm
Yes, but can one create software that will fly and not careen off in random directions or flip?

Multicopter firmware is what lured me into ARM world in the first place.  Very familiar with AVR projects like Multiwii and Ardupilot or even ARM based ones including Timecop's Baseflight and Harakiri. I know there are low end projects too like KK and some of the toy copters but never encountered anything that might be compatible with 003 type MCU. I have quite some stock of MPU6050 and other mems sensors and recently purchased over a hundred of these 003 at bargain price so would love to take advantage in this area. It would be very much appreciated if you could direct me to any image files for this chip such as are published for the other MCUs.
Title: Re: STM32, ghetto style
Post by: dannyf on September 28, 2014, 01:38:45 am
Quote
STM8S003F, doing pwm on tim1, ch3 (PC3).

In comparison, this is STM32L152, doing pwm on tim3, ch3 (PC8).

Vastly different chips, totally different implementation (one via library and another via direct register access). The user code however is identical.

That's the power of middleware.

Title: Re: STM32, ghetto style
Post by: Koepi on September 28, 2014, 05:03:07 am
paulie,

to my knowledge there is no such project public available. You'd need to port a project yourself or take the know-how/documentation of those and completely implement it from scratch for a new MCU.
With some experience in development not a too hard task. But that experience is definatly needed.

dannyf: the class library/middleware makes the coding a breeze. I think the problem for these memory limited cheap MCUs is that these libraries bloat the resulting binary way too much. So it would be better to take the reference data sheet and do more of a bare-metal coding directly with using the registers. Without question you can do that, but there the disadvantage of the many peripherals and complexity shows - compared to a ATmega datasheet, you have way more to read ;)
Title: Re: STM32, ghetto style
Post by: paulie on September 28, 2014, 08:26:34 am
to my knowledge there is no such project public available. You'd need to port a project yourself

How did I know you were going to say that? :)

First of all I'm the fellow insisting this is not possible. It don't sound reasonable to ask me to do something I'm saying can't be done.  If FC firmware were successfully implemented on a 25 cent chip like 003 it would be big news rippling across the globe. Not only the main subject on sites I frequent like multiwii.com and diydrones.com but probably make front page NY Times.

This is not "developmental" or a niche market. Between commercial entities like Syma, WLT, Hubsan, etc. and hobby grade products from the DJI, Hobbyking, bangood, and others we are talking billion dollar sales. These have been the top playthings every year for at least the past six years starting with the low cost IMU sensor revolution. First the heli phenomenon with cheap murata piezo clones then widespread availability of mems devices. Big sales, big money, big news.

Secondly I do have some experience in this area. After experimenting with the top dozen or so DIY platforms and more than one failed attempt at "bare metal" I have a pretty good idea of what's involved. Both in terms of effort and MPU resources. So I have to laugh at the way danny tucks in the word "algorithm" as though it's another blinky and:

Coding is super easy.

LOL. I'm not as impressed by all the photos of an LED with keyboard backdrop as apparently everybody else. Why bother? They all look the same and could be just wired directly to VCC under the board. IMO links to functional toolsets and actual working programs would be far more helpful than cryptic code snippets and unbacked claims. More so than all this "look how smart I am" stuff. Not that I mind that but maybe reinforced with a little hard evidence.
Title: Re: STM32, ghetto style
Post by: dannyf on September 28, 2014, 11:00:13 am
Quote
these libraries bloat the resulting binary way too much.

It can be a problem, more so on the lower-end.

But it doesn't have to: that's where a middle layer offers a great compromise - if it turns out that something is taking up too much space / time due to library uses, you can hand-code it without changing the user code.

I have a filter routine that takes an input and generates a filtered output. Depending on the libraries I linked in, the underlying algorithm could be a simple LPF, or PID process, or a set of code generated by Matlab.

I tend to think that unless you are in a cost conscious situation (ie. your value-add is more in hardware and less in software), you worry about other factors, like speed to market, or maintainability, etc.
Title: Re: STM32, ghetto style
Post by: gnif on September 28, 2014, 11:44:15 am
Hi,

Have not fully read this post through, lots and lots of pages... so if this has already been mentioned then ignore this post.

The standard perhipheral library is a load of crap! It is extremely bloated and performs things an exteremely backwards way. I have been programming on the STM32 since they were originally released, and I am also the original author of the open source stm32flash project for serial flashing.

There are three alternatives to using the std perhipheral lib..

1) Read the docs and write to the registers manually (fastest and smallest code results). Once you get familiar with the registers this usually ends up being the best option.

2) Use libopencm3 (http://libopencm3.org/) (formally libopenstm32), very well written, very easy to use with well written examples and a lot of support.

3) Got space for C++ in your project, use libstm32pp (https://github.com/JorgeAparicio/libstm32pp)... although this project seems to be rather dated with little support.

Personally I opt for option 2 when hacking something together, but when I need raw power, or smaller code, I will configure the registers myself.

Example blinky program

Code: [Select]
#include <libopencm3/stm32/rcc.h>
#include <libopencm3/stm32/gpio.h>

int main(void)
{
  rcc_clock_setup_hsi(&hsi_8mhz[CLOCK_44MHZ]);
  rcc_periph_clock_enable(RCC_GPIOE);
  gpio_mode_setup(GPIOE, GPIO_MODE_OUTPUT, GPIO_PUPD_NONE, GPIO12);
  while(1)
  {
    gpio_toggle(GPIOE, GPIO12);
    for (i = 0; i < 2000000; i++)
      __asm__("nop");
  }
}

A bit shorter no?
Title: Re: STM32, ghetto style
Post by: Koepi on September 28, 2014, 12:47:24 pm
gnif, your second option sounds great, will take a look at it for sure! Have to see which µCs are supported by it. When the resulting code is faster and more slim than SPL code it's the way to go. As reading through bad documented "pure register work" code is a nightmare. ;)
Oh, and thank you for stm32flash, using it daily:
Code: [Select]
MacBook-Air:Release koepi$ ./flash.sh
stm32flash 0.3

http://stm32flash.googlecode.com/

Using Parser : Intel HEX
Serial Config: 57600 8E1
Version      : 0x31
Option 1     : 0x00
Option 2     : 0x00
Device ID    : 0x0444 (STM32F030/F031)
- RAM        : 8KiB  (4096b reserved by bootloader)
- Flash      : 64KiB (sector size: 4x1024)
- Option RAM : 12b
- System RAM : 3KiB

Wrote and verified address 0x08001570 (100.00%) Done.

Just another F030 test, a µC controlled LiIon charger. Real life useable. Based upon a TP4056 chip and a switchable resistor and an added power regulator for the µC power supply with 3.3Volts. Due to lack of motivation of soldering up a 4-digit-7-segment with shift registers, output is via UART for now.

Code: [Select]
Charging with 610 mA. (Vprog 586mV, 36%.)
Charging with 612 mA. (Vprog 587mV, 36%.)
Charging with 610 mA. (Vprog 586mV, 36%.)
Charging with 609 mA. (Vprog 585mV, 36%.)
Charging with 608 mA. (Vprog 584mV, 36%.)
Charging with 609 mA. (Vprog 585mV, 36%.)

The code is very simplistic (and SPL based ;) ):
Code: [Select]
#include "stm32f0xx.h"
#include <stdbool.h>
#include <stdio.h>
#include "main.h"

static char text[255];
volatile uint32_t VREFINT_CAL = 0;
RCC_ClocksTypeDef Clocks;
volatile uint8_t charge_rate=0;
static const int resistance[3] = { 1150, 2300, 4400 };
static const bool transistor1[3] = { 0, 1, 0 };
static const bool transistor2[3] = { 1 ,0 ,0 };


void init(void) {
SystemInit();  // Initialize the System

// ---- Setup PLL for 48 MHz :) ----
RCC_DeInit();
RCC_PLLCmd(DISABLE);
RCC_PLLConfig(RCC_PLLSource_HSI, RCC_PLLMul_12);
// Flash: 1 WaitState for 24MHz < SysCLK < 48 MHz
FLASH_SetLatency(FLASH_Latency_1);
FLASH_PrefetchBufferCmd(ENABLE);
// Set ADC clock to sync PCLK/4->12MHz
RCC_ADCCLKConfig(RCC_ADCCLK_HSI14);
// and turn the PLL back on again
RCC_PLLCmd(ENABLE);
// set PLL as system clock source
RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK);
// ---- End of Setup PLL for 48 MHz :) ----


GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStruct;
ADC_InitTypeDef  ADC_InitStructure;

RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE);

// ADC-init for Temperature probe
ADC_DeInit(ADC1);
ADC_InitStructure.ADC_Resolution = ADC_Resolution_12b;
ADC_InitStructure.ADC_ContinuousConvMode = DISABLE;  // on demand
ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_T1_TRGO;
ADC_InitStructure.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None;
ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;  // 12 bit right aligned
ADC_InitStructure.ADC_ScanDirection = ADC_ScanDirection_Upward;
ADC_Init(ADC1, &ADC_InitStructure);

// ADC calibration; but not used as returned value ends nowhere now...
VREFINT_CAL = ADC_GetCalibrationFactor(ADC1);
ADC_Cmd(ADC1, ENABLE);
ADC_DiscModeCmd(ADC1, ENABLE);

// Resistor switches (PNP FET) on PA0+1
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOA, &GPIO_InitStructure);

// R-Probe on PA2
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_DOWN;
GPIO_Init(GPIOA, &GPIO_InitStructure);

// UART1: Configure PA9 and PA10
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9 | GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOA, &GPIO_InitStructure);

GPIO_PinAFConfig(GPIOA, GPIO_PinSource9, GPIO_AF_1);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource10, GPIO_AF_1);

USART_InitStruct.USART_BaudRate = 57600;
USART_InitStruct.USART_WordLength = USART_WordLength_8b;
USART_InitStruct.USART_StopBits = USART_StopBits_1;
USART_InitStruct.USART_Parity = USART_Parity_No;
USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStruct.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;
USART_Init(USART1, &USART_InitStruct);
USART_Cmd(USART1, ENABLE);

RCC_GetClocksFreq(&Clocks);
}

int main (void) {
init();

sprintf(text, "STM32F030-Charger startup.\r\nHCLK is %ld MHz, PCLK %ld MHz, System %ld MHz, ADC %ld MHz.\r\n", (Clocks.HCLK_Frequency/1000000), (Clocks.PCLK_Frequency/1000000), (Clocks.SYSCLK_Frequency/1000000), (Clocks.ADCCLK_Frequency/1000000));
uart_tx(text);

charge_rate = 0;
if (transistor1[charge_rate]) GPIOA->BSRR = (GPIO_Pin_0);  // Enable FET 1 (2.300 Ohm)
if (transistor2[charge_rate]) GPIOA->BSRR = (GPIO_Pin_1);  // Enable FET 2 (1.150 Ohm)

while (1) {
int stage = read_adc();
int Vmax = (uint32_t)(2000*3280/(1<<12));
int Vprog = (uint32_t)(stage*3280/(1<<12));
int Ibat = (uint32_t) ((1000*Vprog/resistance[charge_rate]*1200) / 1000);
int percent = (uint32_t)(Vprog * 100/Vmax);
sprintf(text, "Charging with %d mA. (Vprog %dmV, %d%%.)\r\n", Ibat, Vprog, percent);
uart_tx(text);
Delay(10000000);
}
}

int read_adc(void) {
uint32_t temp = 0;
ADC_ChannelConfig(ADC1, ADC_Channel_2, ADC_SampleTime_13_5Cycles);

// throw away first result like on AVR? first value seems wrong.
ADC_StartOfConversion(ADC1);
while(ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC) == RESET);

for (uint8_t i = 0; i<16; i++) {  // resampling
ADC_StartOfConversion(ADC1);
while(ADC_GetFlagStatus(ADC1, ADC_FLAG_EOC) == RESET);
temp += ADC_GetConversionValue(ADC1);
}
return ( (temp>>4) );
}

void uart_tx(char *out) {
while (*out) {
while(!(USART1->ISR & USART_FLAG_TXE)) {
// Nothing, really.;
}
USART1->TDR = *out++;
}
}


void Delay(__IO uint32_t nCount) {
  while(nCount--) {
  }
}
Title: Re: STM32, ghetto style
Post by: dannyf on September 28, 2014, 01:11:14 pm
Quote
The standard perhipheral library is a load of crap! It is extremely bloated and performs things an exteremely backwards way.

Quote
2) Use libopencm3 (formally libopenstm32), very well written, very easy to use with well written examples and a lot of support.

What's crap and what's not is quite subjective - not right or wrong.

Foundamentally, the use of libraries is a trade-off between many factors, speed / space and ease of use, documentation, reliability, .... There is no right or wrong answer here. Part of a designer's job is to assess the situation and figure out which way is better in a given application.

Quote
but when I need raw power, or smaller code, I will configure the registers myself.

With that, why don't you implement the following:

1) boot up the chip in hsixpll, construct a random number by reading the lsb of an adc pin and transmit that via usart interrupt.
2) implement that using your direct register access + libopencm3.

We will see how much faster  your code runs, how much smaller it is vs. the St library implementation. Then we can see if it is worth it.

Quote
A bit shorter no?

If you allow the use of a library, I can make it into one line, :).

Title: Re: STM32, ghetto style
Post by: gnif on September 28, 2014, 04:32:52 pm
Quote
The standard perhipheral library is a load of crap! It is extremely bloated and performs things an exteremely backwards way.

Quote
2) Use libopencm3 (formally libopenstm32), very well written, very easy to use with well written examples and a lot of support.

What's crap and what's not is quite subjective - not right or wrong.

You are correct it is subjective, but obviously I am not alone in my opinion as libopencm3 has quite a lot of developers backing and using it, many people, including myself, moved from the std lib because we found it sucked... I started to write my own library before I found libopencm3.

Foundamentally, the use of libraries is a trade-off between many factors, speed / space and ease of use, documentation, reliability, .... There is no right or wrong answer here. Part of a designer's job is to assess the situation and figure out which way is better in a given application.

Quote
but when I need raw power, or smaller code, I will configure the registers myself.

With that, why don't you implement the following:

1) boot up the chip in hsixpll, construct a random number by reading the lsb of an adc pin and transmit that via usart interrupt.
2) implement that using your direct register access + libopencm3.

We will see how much faster  your code runs, how much smaller it is vs. the St library implementation. Then we can see if it is worth it.

Well, obviously it is only if I am trying to squeeze every ounce of performance out of it... in most cases I dont bother, as I stated, it is rare. If you want to go that far you could always go to writing assembler, sometimes it is warranted, but rare.

Quote
A bit shorter no?

If you allow the use of a library, I can make it into one line, :).

Well that is obvious... I was allowing the use of a library, what do you think the 'standard pheriperal library' is?
Title: Re: STM32, ghetto style
Post by: dannyf on September 28, 2014, 04:45:57 pm
Quote
libopencm3 has quite a lot of developers backing and using it,

If you use popularity as a judgment of quality, I wouldn't be surprised if far more people use st's library than libopencm3.

Quote
many people, including myself, moved from the std lib because we found it sucked...

Then take the test I mentioned earlier so you can prove conclusively that libopencm3 produces faster and smaller pieces of code.

Quote
as I stated, it is rare.

So the st libraries are a significant problem that you rarely run into?

I wish I had those problems, :)

Title: Re: STM32, ghetto style
Post by: dannyf on September 28, 2014, 04:48:22 pm
On sucky libraries that take up too much space, maybe you should check out those luminary / TI chips with in-rom libraries.

Zero (flash) space taken.
Title: Re: STM32, ghetto style
Post by: Koepi on September 29, 2014, 06:04:23 am
I got bored yesterday evening, so I built a 4-digit-7-segment and wrote PoC code for the tiny F030.
It's incredibly smooth to control the 7-segment with a fast STMf030 completely in software, in direct comparison to ATtiny/ATmega. The multiplex is working nice and satisfying.

The most amazing thing is that the power supplied via the F030 suffices! :)

Code: [Select]
#include "stm32f0xx.h"
#include <stdbool.h>
#include <stdio.h>
#include "main.h"

static char text[255];
RCC_ClocksTypeDef Clocks;
volatile uint8_t digit[4];

// 'database' of digits
static uint8_t lightup[10]={
0b00000011,  // 0
0b10011111,  // 1
0b00100101,  // 2
0b00001101,  // 3
0b10011001,  // 4
0b01001001,  // 5
0b01000001,  // 6
0b00011111,  // 7
0b00000001,  // 8
0b00001001 };  // 9

void init(void) {
SystemInit();  // Initialize the System

// ---- Setup PLL for 48 MHz :) ----
RCC_DeInit();
RCC_PLLCmd(DISABLE);
RCC_PLLConfig(RCC_PLLSource_HSI, RCC_PLLMul_12);
// Flash: 1 WaitState for 24MHz < SysCLK < 48 MHz
FLASH_SetLatency(FLASH_Latency_1);
FLASH_PrefetchBufferCmd(ENABLE);
// Set ADC clock to sync PCLK/4->12MHz
RCC_ADCCLKConfig(RCC_ADCCLK_HSI14);
// and turn the PLL back on again
RCC_PLLCmd(ENABLE);
// set PLL as system clock source
RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK);
// ---- End of Setup PLL for 48 MHz :) ----


GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStruct;

RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);

// 7-seg on PA0-PA4
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3 | GPIO_Pin_4;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOA, &GPIO_InitStructure);


// UART1: Configure PA9 and PA10
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9 | GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOA, &GPIO_InitStructure);

GPIO_PinAFConfig(GPIOA, GPIO_PinSource9, GPIO_AF_1);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource10, GPIO_AF_1);

USART_InitStruct.USART_BaudRate = 57600;
USART_InitStruct.USART_WordLength = USART_WordLength_8b;
USART_InitStruct.USART_StopBits = USART_StopBits_1;
USART_InitStruct.USART_Parity = USART_Parity_No;
USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStruct.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;
USART_Init(USART1, &USART_InitStruct);
USART_Cmd(USART1, ENABLE);

RCC_GetClocksFreq(&Clocks);

// switch 7-seg on
GPIOA->BSRR = GPIO_Pin_0;  // Vcc on PA0
GPIOA->BRR = GPIO_Pin_1;  // GND on PA1
// PA2: SHCP, PA3: STCP; PA4: DS
}

int main (void) {
init();

sprintf(text, "STM32F030-7Seg startup.\r\nHCLK is %ld MHz, PCLK %ld MHz, System %ld MHz, ADC %ld MHz.\r\n", (Clocks.HCLK_Frequency/1000000), (Clocks.PCLK_Frequency/1000000), (Clocks.SYSCLK_Frequency/1000000), (Clocks.ADCCLK_Frequency/1000000));
uart_tx(text);


while (1) {
for (int i=0; i<10000; i++) {
int temp = i;
for (int j=3; j>=0; j--) {
digit[3-j] = temp % 10;
temp /= 10;
}
for (int k=0; k<2000; k++) {
show_digit();
}
}
}
}

void show_digit (void) {
int temp = 0;
for (int i=0; i<4; i++) {
temp = (((lightup[digit[i]]))<<8) | (1<<(i+4));
push_out(temp);
}
}

void push_out(int output) {
for (int i=0; i<16; i++) {
if (output & (1<<i)) {
GPIOA->BSRR = GPIO_Pin_4;
} else {
GPIOA->BRR = GPIO_Pin_4;
}
GPIOA->BSRR = GPIO_Pin_2;
GPIOA->BRR = GPIO_Pin_2;
}
GPIOA->BSRR = GPIO_Pin_3;
GPIOA->BRR = GPIO_Pin_3;
Delay(600);
}

void uart_tx(char *out) {
while (*out) {
while(!(USART1->ISR & USART_FLAG_TXE)) {
// Nothing, really.;
}
USART1->TDR = *out++;
}
}


void Delay(__IO uint32_t nCount) {
  while(nCount--) {
  }
}
Title: Re: STM32, ghetto style
Post by: dannyf on September 29, 2014, 10:00:33 am
Quote
I built a 4-digit-7-segment and wrote PoC code for the tiny F030.

Nice work.

A couple suggestions:

1) you may want to implement the display in a timer isr - it is periodically called and entirely in the background so you can do whatever in your main loop without the display flickering.
2) I would use a display buffer to hold the segment information - the display routine would read from that buffer which segments to turn on / off. With that, you can display alphanumeric information on the led.

I would also package the code in an easy-to-use module that's both CA and CC capable.
Title: Re: STM32, ghetto style
Post by: Koepi on September 29, 2014, 01:46:41 pm
dannyf, thanks for the inspiration - yes, that's on the todo list, as well as starting with the built-in rtc. Let's see where it takes us with the internal 40kHz oscillator.

Just as a note, I called it PoC (proof-of-concept), because it's a fast prototype to make it work on the lowest possible level, as fast as possible. Adding stuff like timers and so on just adds possible errors at this stage. So that is just something to get the idea / working principle from and then throw that all away and do it right. Kind of rapid prototyping.
Title: Re: STM32, ghetto style
Post by: dannyf on September 29, 2014, 04:54:01 pm
It is true: more complexity means more chances that things can go wrong.

however, it can be managed. My timer routines, for example, involve two functions - plus one isr. tmrx_init() sets up timerx to trigger periodically. tmrx_isr() installs a user isr.

in your case, toy can set up the timer and install led display as the isr. And you are done - you can do anything in main and your display will be updated automatically.

Something like this:

Code: [Select]
#include "tmr14.h"  //use tmr14

void show_digit(void); //update display

int main(void) {
  ...
  //set up tmr14 to update led display periodically
  tmr14_init(TMR_PS_100x, TMR_1ms); //tmr14 initialized to 1ms interval, 100x prescaler => 1 overflow every 100ms
  tmr14_isr(show_digit); //install show_digit() as user isr
  //done

if it helps, I can provide a template to get you started.

edit: fixed some spelling and added an example.
Title: Re: STM32, ghetto style
Post by: dannyf on September 30, 2014, 12:35:59 am
Quote
this is STM32L152

Not ghetto but in case anyone struggles with this, the particular board here is STM32L152RE, used on the Nucleo board.

The chip is actually very new, introduced this March / May. Many IDEs, including Keil uVision and CoIDE, don't have support for it. However, you can simply pick STM32L152RD (and other variety if you wish), and everything works out just fine.
Title: Re: STM32, ghetto style
Post by: westfw on September 30, 2014, 08:03:14 am
The standard perhipheral library is a load of crap! It is extremely bloated and performs things an exteremely backwards way.
You might enjoy "The other ST thread" where I've also been complaining about the STP, and positing some theories that the way it has been deployed is not the way that the original authors had in mind.  In a simple example, I cut size of generated code by about 40% by rearranging the STP source to be "inline" rather than in a separate library.  (starting about here: https://www.eevblog.com/forum/microcontrollers/one-dollar-one-minute-arm-development/msg516710/#msg516710 (https://www.eevblog.com/forum/microcontrollers/one-dollar-one-minute-arm-development/msg516710/#msg516710) )

(and I'll also add a thankyou for stm32flash!)
Title: Re: STM32, ghetto style
Post by: Koepi on September 30, 2014, 08:45:55 am
Well, thanks for the advertisement for that thread, but I see it's from paulie and he's trolling around a lot there. So no joy in that. I dislike to read dumb provocation from a teenager to make others take over his work for his project. May have worked in kindergarden, but will be a show stopper in real life.

Thanks for the inlining hint. It seems like the actual "how do I do the inlining" is still missing, but anyhow. A buzzword more which may help when looking around for binary size reduction.
Title: Re: STM32, ghetto style
Post by: dannyf on September 30, 2014, 11:02:49 am
I would be careful with inlining.

All it does is to trade overhead associated with calling a function with flash space. So you use inlining mostly in two cases:

1) speed is important. This is more pronounced when the function to be inlined is small and frequently called. Inlining for example a fft or ieee1057 would make very little sense.

2) overhead is significant vs. the code's execution: like checking a flag, etc. The st library has quite a few such cases. The ghetto code posted earlier took this approach: rather than using a function that checks the flag, it went directly to the register and checked the flag there -> no overhead.

If you are concerned about space, you generally don't inline the code; If you are concerned about execution time, you generally inline the code.
Title: Re: STM32, ghetto style
Post by: Koepi on September 30, 2014, 11:39:08 am
That's how I know inlining, too. More like a #define or Macro, to insert a function completely at that space and reduce jumps, a bit like loop unrolling (which obviously is not reducing the code size).

Thus I'm interested to know how inlining is done to reduce codesize, not to bloat it. I miss that explanation on the other thread, I just read that functions are repeated in several classes of the SPL and thus some optimizations in that area would be possible.
Title: Re: STM32, ghetto style
Post by: mikerj on September 30, 2014, 11:57:32 am
That's how I know inlining, too. More like a #define or Macro, to insert a function completely at that space and reduce jumps, a bit like loop unrolling (which obviously is not reducing the code size).

Thus I'm interested to know how inlining is done to reduce codesize, not to bloat it. I miss that explanation on the other thread, I just read that functions are repeated in several classes of the SPL and thus some optimizations in that area would be possible.

For very small functions (e.g. that can be implemented in one or two instructions) that are called from many different locations, the overhead from the call and return instructions can add significantly to the memory overhead.  In this specific case inlining can reduce memory requirements.
Title: Re: STM32, ghetto style
Post by: dannyf on September 30, 2014, 12:57:35 pm
Quote
functions are repeated in several classes of the SPL

If so, inlining those functions would likely increase the code size.

I will look into it more later.
Title: Re: STM32, ghetto style
Post by: Koepi on September 30, 2014, 01:05:12 pm
Probably "inlining" is used wrong in that context and means to "streamline" multiple function-instances from different classes to collect them in an extra class - so they appear only once and can be reused everywhere. Just guessing.

(And so small functions which would result in 1-2 machine instructions would more likely be macros, won't they? I can't from top of my head think of having ever seen something like that as function :D )
Title: Re: STM32, ghetto style
Post by: mikerj on September 30, 2014, 04:02:50 pm
(And so small functions which would result in 1-2 machine instructions would more likely be macros, won't they? I can't from top of my head think of having ever seen something like that as function :D )

Small functions like this are used extensively in things like the CMSIS and STM32 libraries in order to provide a level of abstraction. e.g.

Code: [Select]
void GPIO_SetBits(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin)
{
  /* Check the parameters */
  assert_param(IS_GPIO_ALL_PERIPH(GPIOx));
  assert_param(IS_GPIO_PIN(GPIO_Pin));
 
  GPIOx->BSRR = GPIO_Pin;
}

The asserts don't create any code at all unless you define a symbol to enable them, so this function requires two values to be pushed onto the stack prior to calling, the call itself, and then the two stack values used to write a value to the GPIO set register, and then the return back to the calling function.  Inlining a function like this would very likely save some code space.
Title: Re: STM32, ghetto style
Post by: dannyf on September 30, 2014, 05:41:02 pm
I went back to that thread where inlining cuts the code by 40%. I didn't see anything that supports it - it seems that it was talking about a convoluted way of calculating baud rates.

Maybe my browser was acting up but that's what I got.
Title: Re: STM32, ghetto style
Post by: westfw on September 30, 2014, 06:41:01 pm
Quote
I went back to that thread where inlining cuts the code by 40%. I didn't see anything that supports it

The numbers are buried in "code" tags in this post:
https://www.eevblog.com/forum/microcontrollers/one-dollar-one-minute-arm-development/msg518377/#msg518377 (https://www.eevblog.com/forum/microcontrollers/one-dollar-one-minute-arm-development/msg518377/#msg518377)
"USART_DeInit(); USART_Init()" pair: 596 bytes without inlining, 356 bytes with inlining.  40.3% savings. (67% bigger without inlining!)

The detailed explanation, and the sample code that you could download and see for yourself, is in this post: https://www.eevblog.com/forum/microcontrollers/one-dollar-one-minute-arm-development/msg518579/#msg518579 (https://www.eevblog.com/forum/microcontrollers/one-dollar-one-minute-arm-development/msg518579/#msg518579)

The complaint about the baud rate calculation was elsewhere.
Title: Re: STM32, ghetto style
Post by: westfw on September 30, 2014, 08:06:37 pm
You haven't actually inlined anything if you're only including the .h in your main.c...

Title: Re: STM32, ghetto style
Post by: westfw on October 01, 2014, 05:51:06 am
It turns out that there is a simpler way to get partly optimized (inlined) STP code.  Simply include the .c file from the STP modules as well as the .h files:
Code: [Select]
#include "stm32f0xx_rcc.h" //clock routing used
#include "stm32f0xx_gpio.h" //gpio modules used
#include "stm32f0xx_adc.h" //adc module used
#include "stm32f0xx_usart.h" //usart used
#include "stm32f0xx_misc.h" //interrupts used

#ifdef DOINLINE
#include "stm32f0xx_rcc.c" //clock routing used
#include "stm32f0xx_gpio.c" //gpio modules used
#include "stm32f0xx_adc.c" //adc module used
#include "stm32f0xx_usart.c" //usart used
#endif

Doing this for Dannyf's init/adc/uart blinky program shaved off a bit more than 10%, which isn't bad for an essentially zero-effort change.  It didn't improve any using modified STP files, either.  (However, the simple uart deinit/init example, which was crafted to explicitly capitalize on the inline definitions, DID do much better with modified STP source - it only went down about 5% in size with the double-includes.  I'm not sure exactly why...)

Code: [Select]
BillW-MacOSX-2<10307> make dannyn
/usr/local/armgcc/bin/arm-none-eabi-gcc -DSTM32F10X_MD=1 -mcpu=cortex-m3 -mthumb -O3 -ffunction-sections -fdata-sections -Wl,--gc-sections -gdwarf-2 -include assert.h -o danny_normal -DSTM32F030=1 \
           -I normal danny.c \
           normal/stm32f0xx_misc.c normal/system_stm32f0xx.c \
           normal/stm32f0xx_usart.c normal/stm32f0xx_rcc.c \
           normal/stm32f0xx_adc.c normal/stm32f0xx_gpio.c
/usr/local/armgcc/bin/arm-none-eabi-size danny_normal
   text    data     bss     dec     hex filename
   3288    1120      40    4448    1160 danny_normal
BillW-MacOSX-2<10308> make dannyi2
/usr/local/armgcc/bin/arm-none-eabi-gcc -DSTM32F10X_MD=1 -mcpu=cortex-m3 -mthumb -O3 -ffunction-sections -fdata-sections -Wl,--gc-sections -gdwarf-2 -include assert.h -o danny_i2 -DSTM32F030=1 \
           -I normal -DDOINLINE danny.c \
           normal/stm32f0xx_misc.c normal/system_stm32f0xx.c
/usr/local/armgcc/bin/arm-none-eabi-size danny_i2
   text    data     bss     dec     hex filename
   2900    1120      36    4056     fd8 danny_i2
Title: Re: STM32, ghetto style
Post by: dannyf on October 01, 2014, 10:17:03 am
Both inline and non-inline version of USART_DeInit() starts at ~1.4Kb with 1 invocation.

After that, the inlined version goes up 200 bytes per invocation; and the non-inlined version up minimally.

It is consistent with the conventional understanding on what inlining does.

I think the original 40% figure quoted for "inlining" might be for something else.
Title: Re: STM32, ghetto style
Post by: bingo600 on October 01, 2014, 06:49:31 pm
This code from here : (for a F030) using -Os
https://www.eevblog.com/forum/microcontrollers/stm32-ghetto-style/msg522326/#msg522326 (https://www.eevblog.com/forum/microcontrollers/stm32-ghetto-style/msg522326/#msg522326)

Code: [Select]
#include <stm32f0xx.h>
#include "stm32f0xx_usart.h"


int main(void) {
USART_InitTypeDef USART_InitStruct;

USART_DeInit(USART1);
    //USART_Init(USART1, &USART_InitStruct);

while(1) {
    }
}

Gives this result:
Code: [Select]
arm-none-eabi-size main.elf
   text    data     bss     dec     hex filename
    596       0       0     596     254 main.elf

Latest launchpad
Code: [Select]
Thread model: single
gcc version 4.8.4 20140526 (release) [ARM/embedded-4_8-branch revision 211358] (GNU Tools for ARM Embedded Processors)


And the init+blinky+adc-random code from here
https://www.eevblog.com/forum/microcontrollers/stm32-ghetto-style/msg508984/#msg508984 (https://www.eevblog.com/forum/microcontrollers/stm32-ghetto-style/msg508984/#msg508984)

Code: [Select]
arm-none-eabi-size main.elf
   text    data     bss     dec     hex filename
   1396      20       4    1420     58c main.elf

/Bingo
Title: Re: STM32, ghetto style
Post by: westfw on October 02, 2014, 04:01:37 am
The 40% number is for JUST the library code, not including the startup code that compilation normally includes.
Add -nostartfiles to your compile.  Obviously, inlining the STP code doesn't have any effect on the size of the the vector table or C startup code.   The STP code to do the same function does shrink considerably.  (Presumably, the resulting program doesn't actually function correctly with no startup code.  It's just a compilation size experiment.)

Code: [Select]
BillW-MacOSX-2<10344> make nostartn
/usr/local/armgcc/bin/arm-none-eabi-gcc -DSTM32F10X_MD=1 -mcpu=cortex-m3 -mthumb -O3 -ffunction-sections -fdata-sections -Wl,--gc-sections -gdwarf-2 -include assert.h -o test_normal \
           -nostartfiles \
           -I normal main.c normal/stm32f10x_usart.c normal/stm32f10x_rcc.c start.c
/usr/local/armgcc/bin/arm-none-eabi-size test_normal
   text    data     bss     dec     hex filename
    592      36       0     628     274 test_normal
BillW-MacOSX-2<10345> make nostarti
/usr/local/armgcc/bin/arm-none-eabi-gcc -DSTM32F10X_MD=1 -mcpu=cortex-m3 -mthumb -O3 -ffunction-sections -fdata-sections -Wl,--gc-sections -gdwarf-2 -include assert.h -o test_inline \
           -nostartfiles \
           -I inlines main.c start.c
/usr/local/armgcc/bin/arm-none-eabi-size test_inline
   text    data     bss     dec     hex filename
    352      36       0     388     184 test_inline

The .zip file for the whole thing (including multiple versions of the un-modified STP files, for both 030 and 103) is over 500k. :-( I'll put a copy here: https://drive.google.com/file/d/0B6dMB5dovDUZdlFPbzFXemtxZjA/edit?usp=sharing
Title: Re: STM32, ghetto style
Post by: dannyf on October 03, 2014, 10:15:51 pm
Quote
the stm32f7?

Just looked up its datasheet (preview at this time).

Some highlights and low lights:

1) the fpu is a single precision unit;
2) 3x12bit adc, 7.2msps;
3) 18 timers: two advanced (tim1/8) + tim2/3/4/5, each with 4 output compare pins. Wow!
4) 4 usart/4uart: beats out F4 parts but way shy of TI's usart;

Sounds like well featured part. A little bit crippled due to sfpu + small-ish flash. Would be interesting to see how st prices this part.

With parts like this, there will be fewer and fewer reasons to use PIC32.
Title: Re: STM32, ghetto style
Post by: westfw on October 04, 2014, 02:28:24 am
Quote
more explicit
Thanks.  That does help a lot.
There are two reasons that your results are inconsistent with mine:
1) You didn't inline the RCC functions as well.  This is pretty minor; it's a nice trivial function and the call setup is about the same as the inline sequence produced.  No big deal.
2) the big problem is that you missed that for the optimization I'm trying to invoke, the arguments to the inline functions should be CONSTANTS.  Instead of
Code: [Select]
USART_TypeDef *uart;
  uart=USART2;
    :
  myUSART_DeInit(uart);
You should have
Code: [Select]
  myUSART_DeInit(USART2);I'm a little surprised (and disappointed) that gcc doesn't manage to do this optimization even for your original code.  Clearly uart has a constant value and is not volatile or anything; your code and the code with an explicitly constant argument REALLY ought to compile the same :-(

Here's the whole set of possible outcomes.  "MANY" means three calls to DeInit rather than one.
Code: [Select]
( plain )
   text    data     bss     dec     hex filename
   1244    1080      32    2356     934 a.out
-DCONSTANT
   1236    1080      28    2344     928 a.out
-DMANY
   1256    1080      32    2368     940 a.out
-DMANY -DCONSTANT
   1248    1080      28    2356     934 a.out
-DINLINES
   1060    1080      32    2172     87c a.out
-DINLINES -DCONSTANT
   1044    1080      28    2152     868 a.out
-DINLINES -DMANY
   1384    1080      32    2496     9c0 a.out
-DINLINES -DMANY -DCONSTANT
   1084    1080      28    2192     890 a.out


I discovered something else interesting, accidentally.  Want to save 528 bytes of code and 1k of data space (initialized data, so it takes up flash space) in most of your programs?  Define your own exit() function.
Code: [Select]
void exit(int r) {while(1);}  Apparently the standard runtime defaults to a fancy version of exit that calls registered exit procedures.  And that pulls in code to register those procs.  And support functions.  528 bytes worth of code plus over 1000 bytes of "data" to support something that shouldn't happen in an embedded system (calling exit() or allowing main() to return.)  Sigh.

(Edited to include the substantial .data contribution of the default exit()) (Hmm.  It may be that since I'm using a different compile procedure and maybe different STP libs (from the Nucleo downloads, rather than the STP downloads) that  my results are different than others...)
Title: Re: STM32, ghetto style
Post by: Koepi on October 05, 2014, 06:46:19 am
There is something really weird in your setup, it seems.

With self-defined exit()-function:
Code: [Select]
text    data     bss     dec     hex filename
   4914     124     568    5606    15e6 stm32-7seg.elf

And now without:
Code: [Select]
   text    data     bss     dec     hex filename
   4914     124     568    5606    15e6 stm32-7seg.elf

Making main() void instead of int:
Code: [Select]
   text    data     bss     dec     hex filename
   4914     124     568    5606    15e6 stm32-7seg.elf
Title: Re: STM32, ghetto style
Post by: westfw on October 05, 2014, 07:32:26 am
Hmm.  I am using the generic ARM compiler from ARM, which doesn't have ST-specific startup files/etc...
It seems to be sucking in exit() from: arm-none-eabi/lib/armv7-m/libc.a(lib_a-exit.o)
Title: Re: STM32, ghetto style
Post by: westfw on October 05, 2014, 09:50:20 am
Hmm.   So I installed CoIDE and the Windows ARM compiler (4.8.4!) on my windows XP VM, and it does indeed have different behavior WRT exit()/etc.  It also seems to have a memory leak, so that after a dozen or so "rebuild" steps, I get:
Code: [Select]
BUILD FAILED
java.lang.OutOfMemoryError: PermGen space
Total time: 1 second
It seems to add about 2M to the memory usage for each build, and craps out around 190MB total (according to the task manager.)  that seems low, given that the VM has 2G and the system claims 1.5G is still free when CoIDE stops working.  Grr.
Title: Re: STM32, ghetto style
Post by: gmb42 on October 05, 2014, 11:32:05 am
Note that there are some moving parts around for exit().  Depending on your toolchain and how it's setup, it might be using newlib-nano 2 which has a lite option for exit that makes the register and exit functions weak references, so if they aren't used, then the linker doesn't include them

I believe that newlib-nano 2 was introduced with gcc 4.8.  See here (http://www.32bitmicro.com/directory/384-libraries/newlib-nano") for more info.
Title: Re: STM32, ghetto style
Post by: richard_t on October 05, 2014, 03:29:43 pm
Hmm.   So I installed CoIDE and the Windows ARM compiler (4.8.4!) on my windows XP VM, and it does indeed have different behavior WRT exit()/etc.  It also seems to have a memory leak, so that after a dozen or so "rebuild" steps, I get:
Code: [Select]
BUILD FAILED
java.lang.OutOfMemoryError: PermGen space
Total time: 1 second
It seems to add about 2M to the memory usage for each build, and craps out around 190MB total (according to the task manager.)  that seems low, given that the VM has 2G and the system claims 1.5G is still free when CoIDE stops working.  Grr.

There's a fix for that - edit CoIDE.ini (mines in C:\CooCox\CoIDE) to include:

Code: [Select]
--launcher.XXMaxPermSize
256M
-vmargs
-Xms60m
-Xmx512m
-XX:+UseConcMarkSweepGC
-XX:+CMSClassUnloadingEnabled

I put it at the end of that file, and restart CoIDE.

No idea what the above does, I'm not a Java person, but I hope that helps for you.

Richard.
Title: Re: STM32, ghetto style
Post by: westfw on October 05, 2014, 09:05:08 pm
Quote
There's a fix for that
I was hoping there was, but not looking forward to trying to track it down.
Thanks for providing the option.  It seems to work pretty well (there's still some "leak", but it seems to top out at about 240k, and then starts fixing itself...)
Title: Re: STM32, ghetto style
Post by: dannyf on October 05, 2014, 10:34:56 pm
I'm running an older version of  CoIDE (1.7.4 I think) and haven't encounter that issue.

Have yet to find a compelling reason to upgrade, :).
Title: Re: STM32, ghetto style
Post by: IuriC on October 07, 2014, 01:31:22 pm
Nice work guys!

I bought an STM32F4 Discovery board a while back, maybe is time to start play with.
Title: Re: STM32, ghetto style
Post by: Koepi on October 07, 2014, 03:12:17 pm
Iuri, you do realize that there is a "small" difference between a STM32F030 minimalistic board and a F429 Disco? ;)
Title: Re: STM32, ghetto style
Post by: dannyf on October 07, 2014, 03:31:50 pm
There are a few different kinds of STM32F4 boards. CoIDE I think doesn't have full support for them all.

However, you can simply compile to a supported STM32F4 chip (F40x chips for example), as the library makes no distinction between F40x or F41x or F42x chips.

Alternatively, Keil / IAR have full support for all F4 series at this point.

The basic principles outlined earlier should work and the code should also work, with minimum changes.

The F429Discovery is a nice board, with the LCD.
Title: Re: STM32, ghetto style
Post by: Koepi on October 07, 2014, 05:04:21 pm
From the age of the chips and the SPL interface the F0xx and F4xx are close relatives; the F1xx sticks out a bit as it is older and the code/SPL looks a bit different. Especially when you look at the GPIO setup for example, it looks similar, but for example setting up a pin with pullup/pulldown is different.

(I do have the F4-Disco based on F407 as well but it is a bit smaller, thus it wouldn't make my point as clear as the F429 Disco does :D )
Title: Re: STM32, ghetto style
Post by: dannyf on October 07, 2014, 05:17:55 pm
Yeah. F0 has quite a few things going for it: the AF interface is much cleaner; the GPIO flexibility much bigger, and GPIO is hanging off AHB vs. APB....

F1, being quite a bit older, may be refreshed soon.
Title: Re: STM32, ghetto style
Post by: westfw on October 07, 2014, 11:39:37 pm
I also agree that the F0 GPIO interface is "cleaner" than the F1s.  I was shocked on the F1 when I noticed that you had to handle the GPIO bit configuration via separate registers depending on bit number, and then pleasantly surprised when this wasn't the case on F0.
This may be a rare case where (westfw, dannyf, koepi) all agree on something!
Title: Re: STM32, ghetto style
Post by: dannyf on October 10, 2014, 11:55:37 pm
A quick experience in CoIDE vs. Keil.

I am working on an IMU algorithm. 6DOF acceleration / gyro sensors to drive 4 channel pwm generators, uart + bluetooth, lcd, and wii control. Fairly math intensive: the IMU is quaternion driven and the pwm generators are behind a 4x4 PID matrix.

Under CoIDE, it compiles to about 18Kb on a STM32F100 and would not fit into a STM32F030, under the most aggressive optimization.

It compiles to 15Kb on Keil, with no optimization, and down to 8Kb with the most aggressive optimization + Microlib.



Title: Re: STM32, ghetto style
Post by: westfw on October 11, 2014, 07:55:07 am
So... What's twice as big?

I keep seeing reports of "Keil produces much better code than gcc for arm", but no one ever posts are more detailed analysis :-(

Floating point?  I hear that by default, gcc has a relatively bulky SW floating point implementation.  (You can blow an AVR application out of flash space by forgetting the -lm avr float library, and letting it use the gcc float library instead, for instance.  ( http://www.nongnu.org/avr-libc/user-manual/FAQ.html#faq_math (http://www.nongnu.org/avr-libc/user-manual/FAQ.html#faq_math) )
Title: Re: STM32, ghetto style
Post by: dannyf on October 12, 2014, 12:20:28 pm
Not quite ghetto but in the same spirit: Launchpad + mpu6050 + pwm output on a led.

The launchpad reads off mpu6050, perform the fusion + imu algorithm, and use the output (in this case, the accelerometer reading on the X-axis) to dim the led.

The sensor itself is quite sensitive so a little bit of tilting could change the led's brightness significantly.

The mpu is mounted on the base side of the pcb and the led cross two pins. To show the ghetto-ness, no resistor on the led.

Title: Re: STM32, ghetto style
Post by: Koepi on October 12, 2014, 01:32:22 pm
I didn't take a closer look at it yet, but the MSP430G2 launchpad comes with a "spare" µC. It's probably possible to build up something ghetto style abusing a dip socket mount.
Just as blue print, this isn't a working sample, just the idea.

There you could hook up the msp6050 and the LED as well, a few GPIOs are available :)
Title: Re: STM32, ghetto style
Post by: dannyf on October 12, 2014, 10:57:44 pm
That's definitely ghetto  enough, :).

I don't have a MSP430 board - the launchpad I have is one of the earliest ones, with LM4F120.

MSP430 is quite interesting in that the mpu6050 dmp example from Invensense is implemented on msp430 so minimal changes are needed.

Title: Re: STM32, ghetto style
Post by: Koepi on October 13, 2014, 07:28:59 am
Uh, my bad, just realized that you have a Stellaris (=Cortex M3) launchpad there; MSP430 is TIs own low power 16bit processor architecture. I didn't test it yet as I didn't find the motivation to install a suitable IDE and compiler for it.
Unfortunately, the M3 series from TI has been given up end of 2012. LM4F is the supposed Cortex M4 based successor (so your launchpad can't be that old ;) ), but allegedly cheap low-pin-count versions are not yet available.
Title: Re: STM32, ghetto style
Post by: westfw on October 13, 2014, 07:52:43 am
Quote
LM4F is the supposed Cortex M4 based successor
Briefly.  TI gave up the LM prefix and the ARM microcontrollers are now "TIVA TM4Cxxxx"   The LM4F based "stellaris launcpad" was replaced with the "Tiva Launchpad" and has a TM4C123GH6PM to replace the  LM4F120H5QR.  They're ALMOST the same.
Title: Re: STM32, ghetto style
Post by: dannyf on October 13, 2014, 01:22:09 pm
I used a lot of LM3S parts - 8962 for example.

They are (were?) really good mcus with some severe bugs, however.

Luminary is really the first company that started to cheapen 32-bit mcus - they advertised <$1 pricing then - which you could actually buy.

Quote
allegedly cheap low-pin-count versions are not yet available.

LM offered some soic parts - in the LM3Sxxx family for example but they were incredibly difficult to get, even for volume buyers.

TI basically went the upper-market route after they took over. Fortunately, they retained driverlib.
Title: Re: STM32, ghetto style
Post by: dannyf on October 13, 2014, 07:17:56 pm
I have been a staunch critic of ST's i2c implementation.

However, not all is lost. It can be made to work, with some hardware.

Here is a STM32F3 reading acceleration data from a LSM303 (accel + mag) over i2c, @ 100Khz.

Title: Re: STM32, ghetto style
Post by: Koepi on October 13, 2014, 07:57:43 pm
A little off-topic, but this fits the Ghetto Style theme: My neighbour likes fishing a lot. So I ordered some mpu6050s, some piezo buzzers / transducers and built up an Arduino Pro Mini board (don't worry, I use Eclipse/avr-gcc to program it; thus it's more like a comfortable built up ATmega board). Works like charme, though I'm too lazy to implement power saving stuff. Tonight I started the minimizing process - replace dupont wiring with enameled copper wires, isolating with capton tape, using shrink wrap.
Only thing missing is mobile 3.3V power supply. :)

This thing starts beeping with the slightest movement, really nerve wasting. Thus if a fish bites when he has taped this to his fishing pole, he'll be aware of it. Looks ghetto, too!
Title: Re: STM32, ghetto style
Post by: Koepi on October 13, 2014, 08:04:33 pm
dannyf, I totally agree that I2C with STM32F0 is PITA. I tried (succesfully!) communicating with a RDA5807M FM tuner chip (idea: decoding RDS to fetch time information for the RTC of STM32). It was quite some tuning in the I2C parameters for timing and signal processing necessary, but eventually I got it right.

I guess this works with a lot of I2C chips:
Code: [Select]
GPIO_InitTypeDef GPIO_InitStructure;
I2C_InitTypeDef I2C_InitStructure;

// Initialize I2C (PB6 = SCL, PB7 =SDA)
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOB, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1, ENABLE);
RCC_I2CCLKConfig(RCC_I2C1CLK_SYSCLK);
GPIO_PinAFConfig(GPIOB, GPIO_PinSource6, GPIO_AF_1);
GPIO_PinAFConfig(GPIOB, GPIO_PinSource7, GPIO_AF_1);

// I2C Configure pins: SCL and SDA
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_InitStructure.GPIO_OType = GPIO_OType_OD;
GPIO_Init(GPIOB, &GPIO_InitStructure);

I2C_DeInit(I2C1);
I2C_Cmd(I2C1, DISABLE);
I2C_InitStructure.I2C_AnalogFilter = I2C_AnalogFilter_Enable;
I2C_InitStructure.I2C_DigitalFilter = 0x00;
I2C_InitStructure.I2C_OwnAddress1 = 0x00;
I2C_InitStructure.I2C_Mode = I2C_Mode_I2C;
I2C_InitStructure.I2C_Ack = I2C_Ack_Enable;
I2C_InitStructure.I2C_Timing = 0xB0420F13;  // magic!
I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
I2C_Init(I2C1, &I2C_InitStructure);
I2C_Cmd(I2C1, ENABLE);

Edit: Added the LA graph as well.
Title: Re: STM32, ghetto style
Post by: dannyf on October 13, 2014, 09:23:03 pm
I failed to attach the waveform in the earlier post so here it is:

Title: Re: STM32, ghetto style
Post by: dannyf on October 13, 2014, 09:26:32 pm
Quote
I guess this works with a lot of I2C chips:

That's what I do as well.

The frustrating part for me is in the block read/write routines where exception handling varies from family to family - they the NXP approach and "scattered" it randomly.

The Atmel / PIC approach works really well, in comparison.
Title: Re: STM32, ghetto style
Post by: dannyf on October 13, 2014, 09:43:13 pm
Quote
This thing starts beeping with the slightest movement, really nerve wasting.

Looks like an interesting project.

Two ways to control sensitivity:

1) use the motion driver library from invensense. It has a double tap function built-in. You have to register with them, however.

2) if you don't care about energy consumption, you can think of the fishing pole as an "airplane" and you just need to calculate sudden changes in its "flight" parameters. Look into the various IMU algorithms floating around and it is not difficult to adapt it to your application.

A harder approach is to go naked - fuse the accelerometer + gyro data yourself. The difficulty here is drifting: the parametres will drift back and forth by itself so some kind of filtering, with all 6 parameters preferably, would be helpful.

The mpu6050 is an incredible sensor: very sensitive and yet stable. In comparison, the LSM303 / L3GD20 from ST are lacking.
Title: Re: STM32, ghetto style
Post by: Koepi on October 13, 2014, 09:57:18 pm
Hehe  ;D I use a 'moving' average from the last ten samples and if the new sample is above a threshold - which is used as sensitivity tuning parameter - from the average I start the buzzer. Works very well!
The nerve wasting part starts when you are still coding and every key pressed is causing the noise  ;)
Title: Re: STM32, ghetto style
Post by: dannyf on October 13, 2014, 10:18:40 pm
I prefer LEDs, :)

On moving average, not sure if you read from fifo or not but a simple way to perform a moving average is this:

Code: [Select]
  avg += (new_data - avg) >> n;

it is essentially the binary implementation of this:

Code: [Select]
  avg = avg * (1-weight) + new_data * weight;

where "weight" is 1/2^n.

It requires little data and can be done quickly, even on lowly 8-bitters.

n effectively controls the memory of the filter: the higher the n, the longer it remembers the past and the slower its output changes with new data.

Hope it helps.
Title: Re: STM32, ghetto style
Post by: dannyf on October 13, 2014, 10:20:42 pm
wavefrom of reading DS3231 using a ghetto board's I2C1 running at 100Khz.

The i2c address is 0xd0 / 0x68, depending on your notational system.

edit: needed to point out there there is no device on the bus when this picture was taken -> thus no ack for the address sent.
Title: Re: STM32, ghetto style
Post by: dannyf on October 13, 2014, 10:26:10 pm
Incomplete without showing the ghetto connection: :)

The ds3231 is an ebay knock-off: it is off about 1 minute per month -> 20ppm actual vs. 2ppm spec, :)
Title: Re: STM32, ghetto style
Post by: Koepi on October 14, 2014, 08:22:47 am
Funny that you mention it, today I did some research on fixing my cheap DS1307 boards which are 30 minutes off after half a year now. That was one of my first µC projects, to build a watch using I2C communication, controlling a 4digit 7segment LCD, measuring Vcc as well as temperature with the built-in peripherals, using power-save modes and run that on a 18650 LiIon cell - runs a month straight with one charge!
I have the same DS3231 PCB still waiting in it's ESD protection pouch. Wanted to fix the DS1307 with soldering the crystal to the GND area and maybe replace it with a better suiting one (next to solder an additional 10µF tantal + 0.1µF ceramic capacitor to Vcc; also shortening the jumping wires from 8" to way less length for the SDA/SCL lines) as first attempt before throwing those parts into trash. :D

On a sidenote, I use the "Pin13" (PinB5) LED on the Arduino board for feedback as well, so it's an "audio visual bite indicator". :D
Title: Re: STM32, ghetto style
Post by: dannyf on October 14, 2014, 11:23:32 am
Quote
"audio visual bite indicator"

It wouldn't suprise me if there is a market for something like that: use a pot / button to adjust sensitivity + button to adjust chirping pattern.

A cheaper version for regular fishermen and a more expensive, multi-sensor version for sea fishermen.
Title: Re: STM32, ghetto style
Post by: paulie on October 14, 2014, 05:07:38 pm
Wanted to fix the DS1307 with soldering the crystal to the GND area and maybe replace it with a better suiting one (next to solder an additional 10µF tantal + 0.1µF ceramic capacitor to Vcc; also shortening the jumping wires from 8" to way less length for the SDA/SCL lines) as first attempt before throwing those parts into trash. :D

I can tell you from experience there is no hope for 1307 accuracy in a typical environment. The only way to adjust frequency is changing the caps on each end or write complicated auto-correct software which needs to be updated periodically from an atomic reference. Then there's that temperature thing which needs a sensor somewhere in the system.

The only thing going for it is low cost. Not worth it. In my opinion pay a little more for the compensated one or just hook a 32khz crystal up to the MCU. A buddy of mine built a RTC with 7 segment similar to you but with STM32F103C only. Same battery too. After 4 months less than 3 seconds off. Cheaper and more accurate than either of those chips.

ps. I should have listened to his sales pitch when he was trying to convince me back then but thought the tools were nasty just like the architecture. Little did I know...
Title: Re: STM32, ghetto style
Post by: Kjelt on October 14, 2014, 06:00:34 pm
Darn is that 1307 that bad? I am just using the 1337 probably the same?
The AN58 states that the crystal should be matched and that the accuracy is between 0 and 40 degrees C <10ppm?
Maybe you have the wrong crystal match?
Title: Re: STM32, ghetto style
Post by: paulie on October 14, 2014, 06:17:33 pm
Yes, they really are that bad. Compounded by one of those rare cases where the cheap Chinese IC and crystal knockoffs may be making things worse. It's true that using bona fide source and specific crystal part number may help but then you end up paying an arm and a leg.

IMO using the built-in RTC feature specifically designed into STM32 for this purpose is the best path. Not good for Arduino enthusiasts with their ready to go "sketches" and "shields" but great for the new generation of ARMduinos. :)
Title: Re: STM32, ghetto style
Post by: dannyf on October 14, 2014, 07:45:39 pm
Quote
Maybe you have the wrong crystal match?

Likely. The 1307 requires a stable crystal, and matched capacitance to work. 323x assures the matching and on top of it provides temperature compensation.

Feeding the 32Khz output from the 323x to the 1307 will get you equally good results.

Plus, there are ways to compensate for timing errors in 1307, with a mcu.
Title: Re: STM32, ghetto style
Post by: Koepi on October 14, 2014, 08:29:11 pm
Damn, I have several RTCs around. My clock was off 30 minutes after half a year - which has to be considered quite good when asking around; many RTCs are that bad in less than a month.
When I returned from work and took a look at the board I used, I had to laugh: It's a DS1302. And what do you guess, as if I knew about this thread back then, that China board is real ghetto style. The DS1302 as DIP version, a 32.768kHz crystal (unclear whether it is matched to suite 6pF) and a battery. That's all, no additional components. According to the data sheet, that should work. But it doesn't (properly).

What I did now is: Add 100nF+1µF ceramic capacitor to Vcc2 (-> power from µC). Added 100nF for Vcc1 (battery). Put a big solder blob below the crystal. As GND is the plane on the other PCB side, used an enameled copper wire connection to contact that blob to GND.
Additionally replaced some dupont wires with enameled copper wires so the distance is reduced; in fact, I isolated the backside of the Arduino board and taped the RTC board against it. Now only the 4-digit 7-segment has 8 dupont wires left; the common cathodes are connected with enameled copper wire now, too.

For now the result looks good. Set the time around 7P.M., now three hours later there is no noticable drift from the 12-13 seconds I set it too late. Have to watch it a few days though. Edit: 12 hours later, I see 1-2s drift again; would sum up to ~4s/day, 2 minutes/month, 12 minutes/half year and thus be an improvement at least. I'll keep on monitoring and probably will update this post later again ;)
Took the time to clean up the code I used back then. I had it nearly right, doing stuff between several timestamps (milliseconds) - but did that in the ISR instead of the mainloop. A few more volatile variables later, this is close to proper code now :D
Title: Re: STM32, ghetto style
Post by: dannyf on October 15, 2014, 09:54:53 am
Quote
would sum up to ~4s/day

If it is consistently off 4s/day, you can compensate for it quite easily: for example, set up a daily alarm and retard timing by 4s once it goes off; or (my preferred way), write the last time you retarded timing in the ram and ever N seconds later (N being sufficiently large, like 1 million), you retard or advance timing by a set amount, and write the time you altered the timing into the ram.

It allows accurate timing down to sub ppm levels.

Useful however only if the rtc works in a stable (temperature wise) environment. Otherwise, the temperature drift will overwhelm.
Title: Re: STM32, ghetto style
Post by: Koepi on October 16, 2014, 05:00:12 pm
Just implemented that now - added a write routine for the DS1302 and set the CLK_HLT bit at 18:10:00 and clear it at 18:10:03. I think that those modifications led to a more stable and correct timing. The DS1302 is a pure timekeeper and offers no alarms, though, so I needed to do that in my huge if..then..elseif.. construct which I use as main loop.
I need to play with STM's built-in RTC though. When I try tweaking powersave, refreshing/lighting up the 4digit 7segment every ms, thus using timer2 (which is available in powersave mode), I can't get clear frequencies like 1ms. I get 778Hz, 1.11 kHz, 3.34kHz and similar, but nothing even. I hope with the F030 RTC for example, I can put the µC to sleep and wake it via RTC interrupt every ms. Which would once more beat the sh** out of old and much more expensive ATmega. :)
Title: Re: STM32, ghetto style
Post by: dannyf on October 16, 2014, 05:56:34 pm
Quote
STM's built-in RTC

ST implemented RTC modules fairly inconsistently - almost purposefully inconsistently. Some of them are full featured, but the one in F030 is bare minimum - it is simply a counter. No second isr, for example.

Title: Re: STM32, ghetto style
Post by: Koepi on October 16, 2014, 06:51:20 pm
Hm, the data sheet doesn't imply it's not available on the F030:

Code: [Select]
6.3.6 RTC wakeup from low-power mode
The RTC can be used to wakeup the MCU from low-power mode by means of the RTC
alarm. For this purpose, two of the three alternative RTC clock sources can be selected by
programming the RTCSEL[1:0] bits in the RTC domain control register (RCC_BDCR):
? Low-power 32.768 kHz external crystal oscillator (LSE OSC)
This clock source provides a precise time base with very low-power consumption (less
than 1µA added consumption in typical conditions)
? Low-power internal RC Oscillator (LSI)
This clock source has the advantage of saving the cost of the 32.768 kHz crystal. This
internal RC Oscillator is designed to add minimum power consumption.
To wakeup from Stop mode with an RTC alarm event, it is necessary to:
? Configure the EXTI Line 17 to be sensitive to rising edge
? Configure the RTC to generate the RTC alarm
To wakeup from Standby mode, there is no need to configure the EXTI Line 17.

Source: STM32F030 Reference Manual (http://www.st.com/web/en/resource/technical/document/reference_manual/DM00091010.pdf), Page 73/655 at the bottom.

You'd need to set an alarm for every next second though, to have a "every second ISR". Not really elegantly solved.
Title: Re: STM32, ghetto style
Post by: dannyf on October 16, 2014, 07:56:35 pm
The give-away is in the interrupt section: no second overflow interrupt for the rtc.

Yes, setting up the alarm is the only way to go.

Because of that, I don't think the rtc on F030 is much useful.
Title: Re: STM32, ghetto style
Post by: dannyf on October 18, 2014, 11:44:48 am
I wrote in a separate thread that with a timer you could fairly easily constitute a multi-channel pwm generator on a PIC.

The same can be done on a stm32f as well - normally, there are more than sufficient hardware pwm channels on a stm32f - 12 on a puny STM32F030F4 for example.

There are timers on STM32F that don't have output compare capabilities - typically on TIM6/7. With the help of software, those timers can be easily turned into pwm generators as well:

1) set up timer to trigger isr periodically;
2) in the isr, increment a counter;
3) on each increment, test for pins where the desired duty cycle is the same as the counter's current value and set/clear the corresponding output pin.

Here is its implementation on the ghetto board (STM32F030), two channel 50Hz pwm.
Title: Re: STM32, ghetto style
Post by: dannyf on October 18, 2014, 11:45:48 am
Here, two channel pwm at 400Hz.
Title: Re: STM32, ghetto style
Post by: dannyf on October 18, 2014, 11:47:30 am
As the implementation is entirely done in the isr, it is fully transparent to the user. From that perspective, it behaves just like a hardware pwm generator.

Unlike a hardware pwm generator, however, it does take a way the mcu's processing power. And the smaller the timing steps, the more processing power it consumes. As such, this approach is more suited for low frequency pwm.
Title: Re: STM32, ghetto style
Post by: Koepi on October 25, 2014, 03:08:07 pm
I'm playing around a little with LDOs and switching regulators. Now the power supply for the stm32f030-boards can be done ghetto-style as well (just look how bad my soldering skills are :D ).

The first three pictures show how to build up a PAM3101 LDO; I used a MiniUSB-connector for power input via USB. I added more Vout/GND pins so peripherals can be powered with it, too. It copes with a 4 digit 7-segment display as well. It has no issues with little load around 10-40mA (up to Imax, around 250mA), this is something cheap LDOs have issues with (like AMS1117).

The last picture shows a smaller footprint RT9166 LDO "breakout" board. It delivers power for my soft-PWM-dimming LED sample f030 board, also down to 5mA with no issues (Imax around 300mA). Both work stable, and from the amount of connections and solder points the RT9166 version is the preferred one to put it for example directly on a TSSOP20-2-DIP board with F030 µC.

The RT9166 costs around 10 cents each (at Aliexpress 30 pieces for 3 bucks including shipping around the globe). It delivers great, low noise, very low dropout current. I'll test a few more ICs soon, as MCP1700 promise even less quiescent current draw.

I'm looking out for NCP 1402SN 33/50; with those, I can use a single mignon alkaline cell to provide power for a circuit. With quite amazing efficiency. Those are around 40cents per IC though.
Title: Re: STM32, ghetto style
Post by: dannyf on October 25, 2014, 07:38:45 pm
1117s (both knock-offs and ld1117) are my favorite low-current regulator. I buy them in the hundreds and they are cheaper than discrete transistors.

Would love to try RT9166 when I get a chance. Used MCP1700 a few times and didn't find a compelling reason to use them.
Title: Re: STM32, ghetto style
Post by: Koepi on October 25, 2014, 09:31:18 pm
I'm just checking if I manage to see a difference between all those LDOs and power supply mechanisms in practice, thus I ordered plenty different ICs.
Those RT9166 are quite cheap as well:
http://www.aliexpress.com/snapshot/6256602707.html (http://www.aliexpress.com/snapshot/6256602707.html)
Of course, you get 100+ AMS1117 for that price tag. But they're less precise and effective and have a significant higher dropout voltage. Relevant only if you thin about using 3 AA batteries or LiIon as power source, of course. :) What bothers me most with 1117 is the minimum load of 5-10mA.
Title: Re: STM32, ghetto style
Post by: Kjelt on October 25, 2014, 10:22:58 pm
What bothers me most with 1117 is the minimum load of 5-10mA.
Lets be clear here (for my understanding at least).
Looking at the datasheet of the quiescent current of a LD1117 (link below) that is 5 to 10mA.
The minimum load however is typ. 2mA.
So you probably mean that the quiescent losses are 5 to 10mA which bothers you, not the minimum output current?

http://www.farnell.com/datasheets/1776449.pdf (http://www.farnell.com/datasheets/1776449.pdf)
Title: Re: STM32, ghetto style
Post by: Koepi on October 25, 2014, 10:49:06 pm
You're looking at a different datasheet. Talking about the 3-cents AMS1117:
http://www.advanced-monolithic.com/pdf/ds1117.pdf (http://www.advanced-monolithic.com/pdf/ds1117.pdf)

Minimum load 5-10mA, quiescent current the same range. The more expensive "original" IC has a little better data but still is not as good as for example a RT9166.

Driving a circuit in mobile conditions (=on battery power) which uses 2.6mA like for example the 4-digit 7-segment LED clock I built, that is way to much wasted energy and even out of specs when using a 1117.
I took an ATmega328 in Arduino Pro Mini format, as it has a wide input voltage range from 1.8-5V and thus can be fed directly with a LiIon battery. With an efficient LDO/boost/whatever power supply, I could do this with a cheap F030 and one or two AA batteries.
Title: Re: STM32, ghetto style
Post by: Kjelt on October 25, 2014, 10:53:32 pm
Ok I thought you said 1117 as in any 1117 LDO VR.
Title: Re: STM32, ghetto style
Post by: Koepi on October 25, 2014, 10:55:18 pm
I did in the last sentence. I thought they all behave the same, but there are obviously tiny differences. Not really much, not enough to change usability significantly.
Title: Re: STM32, ghetto style
Post by: dannyf on October 26, 2014, 11:43:40 am
I did a quick testing of a couple LD1117/3.3v regulators (to220) I have.

3.28 - 3.30v output, no load attached. Rock solid output;

5.0 - 5.2ma idle current.

I don't have much complaints about 1117 regulators in general, given their low low prices. However, my application is mostly desktop so idle current isn't a concern. I can understand that for a battery powered application, 5ma maybe a little on the high side.
Title: Re: STM32, ghetto style
Post by: dannyf on October 26, 2014, 11:45:19 am
At some point, a regulator shoot-out may be interesting to see. We can pick a few easy to measure attributes and we can go through our own parts box and find some interesting regulators to test.
Title: Re: STM32, ghetto style
Post by: Koepi on October 27, 2014, 09:56:55 pm
Huh, there was trash on TV tonight (which my wife wanted to watch), so I took the chance to build up the three different LDOs I have flying around as single ICs and do first measurements. A bit OT, but as it fits into the discussion and dannyf suggested it ...  ;D

I used only X7R ceramic capacitors; the GND "plane" is done with fat solder blob or fat wire. Other wiring is done with 0.1mm enameled copper wire.

LDOVout *1Current *2
PAM31013.292V59,8µA
RT91663.285V6.3µA
MCP1825S3.335V44.1µA
*1 Output voltage with STM32F030 attached doing software PWM with 100kHz+,  load between 20-40mA
*2 Without any load attached.


The PAM3101 really sucks to build up - you need three capacitors and puzzle that together in very little space.
On the photo from left to right: MCP1825S, RT9166 and PAM3101.
Title: Re: STM32, ghetto style
Post by: Ribster on November 01, 2014, 01:16:39 pm
Set up HSIxPLL:
...
That's 64 million reasons to get this little bugger, :)

Hey guys,
I'm trying the STM32F051C8T6.
For a while i'm trying to get the HSI as clock source, but it doesn't work to get it going.
I've used this piece of code directly inside my system_stm32f0xx.c file:
Code: [Select]
RCC_DeInit(); //reset rcc
RCC_PLLCmd(DISABLE); //disable PLL
RCC_HSICmd(ENABLE); //enable hsi;
RCC_HCLKConfig(RCC_SYSCLK_Div1); //set sysclk divider
RCC_PLLConfig(RCC_CFGR_PLLSRC_HSI_Div2, RCC_PLLMul_12); //configure pll / divider. _x=[2..16]
RCC_PLLCmd(ENABLE); //enable pll
while (RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET) continue; //wait for pll to be ready
RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK); //set pll as sysclk
while (RCC_GetSYSCLKSource() != RCC_CFGR_SWS_PLL/*0x08*/) continue; //wait for PLL to be ready

SystemCoreClockUpdate(); //update SystemCoreClock

When i let an LED come on before the "while (RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET) continue;   //wait for pll to be ready", it lights up, but flickers.
So i guess it resets on the watchdog because the while loop goes on forever.
Now my question: why can't i select my HSI as PLL clocksource. Am i doing something wrong ?
This chip is good for 48MHz, so multiplier of 12 should be okay. I've tried multiplier of 6, but same result..

Greetings
Title: Re: STM32, ghetto style
Post by: dannyf on November 01, 2014, 02:19:10 pm
I think that's my code for stm32f030f -> but they are in the same family so it should work - it doesn't check for wait state and that's something you may want to address.

I don't change system files, like system_stm32f0xx.c. Instead, in user main(), I put a routine that sets up the mcu, including the clock.

You should try that and see if it works. The way to check is to step through the pll set up section of your code and see if SystemCoreClock has the right value.

Hope it helps.
Title: Re: STM32, ghetto style
Post by: Ribster on November 01, 2014, 02:27:56 pm
Yeah, he keeps hanging on the wating for PLL getting ready.
I wish there was some kind of good tutorial about this.
All the documentation for STM32 is quite extensive, which makes it a bit hard to search for what you exactly want.
The small simple things are documented on other peoples blogs, but this stuff is mostly left out.. Which is a shame..
I'll look further and post a solution once i found one.

Greetings
Title: Re: STM32, ghetto style
Post by: Koepi on November 01, 2014, 02:45:17 pm
What happens if you try this code snippet?


Code: [Select]
// ---- Setup PLL for 48 MHz :) ----
RCC_DeInit();
RCC_PLLCmd(DISABLE);
RCC_PLLConfig(RCC_PLLSource_HSI, RCC_PLLMul_12);
// Flash: 1 WaitState for 24MHz < SysCLK < 48 MHz
FLASH_SetLatency(FLASH_Latency_1);
FLASH_PrefetchBufferCmd(ENABLE);
// Set ADC clock to internal HSI 14MHz
RCC_ADCCLKConfig(RCC_ADCCLK_HSI14);
// and turn the PLL back on again
RCC_PLLCmd(ENABLE);
// set PLL as system clock source
RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK);
// ---- End of Setup PLL for 48 MHz :) ----

This sets clock to HSI and the PLL.
Title: Re: STM32, ghetto style
Post by: Ribster on November 01, 2014, 08:08:43 pm
I've tried it, with the same result.
My leds keep flashing, so the MCU keeps crashing and restarting.
After programming the MCU also disconnects from programmer, picture added.

The only problem that i had, was that i couldn't use the flash functions.
I've added #include "stm32f0xx_flash.h", with no result. My compiler does not find the routines in the corresponding .c file.
Which is very weird. I know eclipse has it's quirks, but this one i don't understand.
Thanks for the help, i'll continue my search..
Title: Re: STM32, ghetto style
Post by: dannyf on November 01, 2014, 08:30:04 pm
Quote
My leds keep flashing, so the MCU keeps crashing and restarting.

Not sure how your code works so not much can be read from the fact that "the led keep flashing"

Quote
After programming the MCU also disconnects from programmer, picture added.

Typically from the swd pins being used by the code.

Quote
The only problem that i had, was that i couldn't use the flash functions.
I've added #include "stm32f0xx_flash.h", with no result. My compiler does not find the routines in the corresponding .c file.

Include the .c files in your project and have the .h files in the include path.

If I were you, I would post a minimalist but complete piece of code so that others know what you are talking about.

As to wait state, I ran a stm32f030f up to 50+Mhz on 0 wait state so it is fairly tolerant.
Title: Re: STM32, ghetto style
Post by: dannyf on November 02, 2014, 02:06:36 pm
Thanks for the help, i'll continue my search..

Liked the sublime style. Did you do it in eclipse or just used sublime as the external editor in eclipse?
Title: Re: STM32, ghetto style
Post by: Koepi on November 02, 2014, 02:46:47 pm
Continued the test, built up a MCP1700 today. This one is amazing!

LDOVout *1Current *2
PAM31013.292V59,8µA
RT91663.285V6.3µA
MCP1825S3.335V44.1µA
MCP17003.283V1.3µA
*1 Output voltage with STM32F030 attached doing software PWM with 100kHz+,  load between 20-40mA
*2 Without any load attached.


It's the second part from the left on the attached photo.
Title: Re: STM32, ghetto style
Post by: dannyf on November 02, 2014, 03:26:36 pm
1.3ua is pretty impressive, especially in ghetto style, :)

Drop out voltage of 150-180mv is pretty good too.
Title: Re: STM32, ghetto style
Post by: Ribster on November 02, 2014, 09:58:58 pm
Thanks for the help, i'll continue my search..

Liked the sublime style. Did you do it in eclipse or just used sublime as the external editor in eclipse?

Nope, fully in Eclipse. The sublime text theme is quite nice. Although i have had some issues with the background for popups.
Personally, its the best syntax coloring for an IDE that i can think of.

EDIT: found the resource link ;) -   Eclipse Color Theme   0.13.1.201405041302   com.github.eclipsecolortheme.feature.feature.group   GitHub
Title: Re: STM32, ghetto style
Post by: dannyf on November 02, 2014, 10:23:58 pm
Sublime has the best visual.

I wish you could invoke such a theme in Source Insight.
Title: Re: STM32, ghetto style
Post by: Ribster on November 02, 2014, 10:29:16 pm
Quote
My leds keep flashing, so the MCU keeps crashing and restarting.

Not sure how your code works so not much can be read from the fact that "the led keep flashing"

Quote
After programming the MCU also disconnects from programmer, picture added.

Typically from the swd pins being used by the code.

Quote
The only problem that i had, was that i couldn't use the flash functions.
I've added #include "stm32f0xx_flash.h", with no result. My compiler does not find the routines in the corresponding .c file.

Include the .c files in your project and have the .h files in the include path.

If I were you, I would post a minimalist but complete piece of code so that others know what you are talking about.

As to wait state, I ran a stm32f030f up to 50+Mhz on 0 wait state so it is fairly tolerant.

Okay, have had a busy weekend with another project. Sorry for the late feedback.
Code for main.cpp that i used:
Code: [Select]
#include <stdio.h>
#include "stm32f0xx.h"
#include "stm32f0xx_flash.h"

void delay(long int delaytime){
for(long int i=0; i<(delaytime*10000000);i++){

}
}

int
main(int argc, char* argv[])
{

RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);
GPIO_InitTypeDef gis;
gis.GPIO_Mode = GPIO_Mode_OUT;
gis.GPIO_OType = GPIO_OType_PP;
gis.GPIO_Pin = GPIO_Pin_12;
gis.GPIO_PuPd = GPIO_PuPd_NOPULL;
gis.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&gis);


// ---- Setup PLL for 48 MHz :) ----
RCC_DeInit();
RCC_PLLCmd(DISABLE);
RCC_PLLConfig(RCC_PLLSource_HSI, RCC_PLLMul_2);
// Flash: 1 WaitState for 24MHz < SysCLK < 48 MHz
//FLASH_SetLatency(FLASH_Latency_1);
//FLASH_PrefetchBufferCmd(ENABLE);
// Set ADC clock to internal HSI 14MHz
RCC_ADCCLKConfig(RCC_ADCCLK_HSI14);
// and turn the PLL back on again
RCC_PLLCmd(ENABLE);
// set PLL as system clock source
RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK);
// ---- End of Setup PLL for 48 MHz :) ----


  // Infinite loop
  while (1)
    {
  delay(100);
  GPIOA->BSRR = GPIO_Pin_12;
  delay(100);
  GPIOA->BRR = GPIO_Pin_12;
    }

  return 0;
}

So my IDE is eclipse with gcc-arm-none-eabi-4_8-2014q2.
I'm using the eclipse wizard that sets up a project in C++ with all the necessary includes and .c-files.
Reference:   GNU ARM C/C++ STM32Fx Project Templates   2.1.1.201404240550   ilg.gnuarmeclipse.templates.stm.feature.group   Liviu Ionescu
I've stripped everything from the code and just using the linked main.cpp file as above.
The chip is the STM32F051C8T6 on a custom board, its the LQFP48 board.
I'm using the HSE pins for something else, assuming i can get the HSI to work.. (That was the plan though..)
Connected via GDB and the STLINK utility from texane (yep, on OS X).
Have had other projects running without any problem, but since i made this custom board with HSI, these problems.
STLink V2 genuine from ST, so no fake. Genuine STM32F0's ordered from mouser. (So i'm using no fake, hate fake in the development fase.)

I've stepped through my code and find that this gives me the error:
Code: [Select]
void RCC_PLLCmd(FunctionalState NewState)
{
  /* Check the parameters */
  assert_param(IS_FUNCTIONAL_STATE(NewState));
 
  if (NewState != DISABLE)
  {
    RCC->CR |= RCC_CR_PLLON;
  }
  else
  {
    RCC->CR &= ~RCC_CR_PLLON;
  }
}
I step through my code, everything goes well, until my PLL-bit gets set and then i lose everything. ->>RCC->CR |= RCC_CR_PLLON;
When i was talking about the led, i let an LED light up right before the PLL configuration, and the led flashes very dim.
What i think that happens is that it just resets and goes into an infinite loop..
I'm having the necessary decoupling caps on the bottom side of the PCB right below the pins with via's.
0402 caps with 1 tantalum as per datasheet. (did my research).
I'm really scratching my head on this one.
When i'm going into the system_stm32f0xx.c file, i see that the SetSysClock routine sets the HSE bit on, waits for the HSE to get ready and then bails out.
I've found adjusted SetSysClock routines that incorporate compiler directives to adjust for the HSI in the first go, but i guess doing this in main() does the same thing..

I hope this is enough info..
Title: Re: STM32, ghetto style
Post by: dannyf on November 02, 2014, 11:23:27 pm
I am running CoIDE/gcc. I didn't do it but the code should yield the same results on keil / iar.
Title: Re: STM32, ghetto style
Post by: dannyf on November 02, 2014, 11:35:42 pm
Koepi's code also worked, in case you are wondering.
Title: Re: STM32, ghetto style
Post by: westfw on November 02, 2014, 11:40:23 pm
Quote
built up a MCP1700 today. This one is amazing!
Available in TO92, too!
Title: Re: STM32, ghetto style
Post by: Ribster on November 03, 2014, 12:20:26 am
I don't have your chip so I cannot tell you how it will work on a F05.

However, I tried the following on a F03 chip and it works as expected.

Here is the code:

Code: [Select]
#include <stm32f0xx.h> //stm32f030f4
#include "stm32f0xx_rcc.h" //we use rcc
#include "gpio.h"

//connection
#define LED_PORT GPIOA
#define LED_A (1<<1)
#define LED_C (1<<2)

void SystemCoreClockHSIPLL2(uint32_t RCC_PLLMul_x) {
RCC_DeInit(); //reset rcc
RCC_PLLCmd(DISABLE); //disable PLL
RCC_HSICmd(ENABLE); //enable hsi;
RCC_HCLKConfig(RCC_SYSCLK_Div1); //set sysclk divider
//RCC_PCLK1Config(RCC_HCLK_Div1); //set pclk1/2 dividers
//RCC_PCLK2Config(RCC_HCLK_Div1);
/**

* @brief  Configures the PLL clock source and multiplication factor.
* @note   This function must be used only when the PLL is disabled.
*
* @param  RCC_PLLSource: specifies the PLL entry clock source.
*          This parameter can be one of the following values:
*            @arg RCC_PLLSource_HSI_Div2: HSI oscillator clock selected as PLL clock source
*            @arg RCC_PLLSource_PREDIV1: PREDIV1 clock selected as PLL clock entry
*            @arg RCC_PLLSource_HSI48 HSI48 oscillator clock selected as PLL clock source, applicable only for STM32F072 devices
*            @arg RCC_PLLSource_HSI: HSI clock selected as PLL clock entry, applicable only for STM32F072 devices
* @note   The minimum input clock frequency for PLL is 2 MHz (when using HSE as
*         PLL source).
*
* @param  RCC_PLLMul: specifies the PLL multiplication factor, which drive the PLLVCO clock
*          This parameter can be RCC_PLLMul_x where x:[2,16]
*
* @retval None
*/
RCC_PLLConfig(RCC_CFGR_PLLSRC_HSI_Div2, RCC_PLLMul_x); //configure pll / divider. _x=[2..16]
RCC_PLLCmd(ENABLE); //enable pll
while (RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET) continue; //wait for pll to be ready
RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK); //set pll as sysclk
while (RCC_GetSYSCLKSource() != RCC_CFGR_SWS_PLL/*0x08*/) continue; //wait for PLL to be ready

SystemCoreClockUpdate(); //update SystemCoreClock
}

//delays some
void delay(uint32_t dly) {
while (dly--) NOP();
}

int main(void) {
mcu_init();
SystemCoreClockHSIPLL2(RCC_PLLMul_12); //go to 48Mhz
PIN_SET(LED_PORT, LED_A); PIN_OUT(LED_PORT, LED_A);
PIN_CLR(LED_PORT, LED_C); PIN_OUT(LED_PORT, LED_C);
while(1) {
PIN_FLP(LED_PORT, LED_A | LED_C);
delay(100000);
    }
}

In addition to SystemCoreClock, the speed at which the led is blinked varies visibly as I change the PLL multiplier.

So your issues are probably somewhere else.

Tried it and again it fails with the PLL enabling.
Fixed the flash referencing thing though, apparently i had a filter set on my source folders  :palm: .
I'm gonna swap the chip out tomorrow with a new one, maybe the chip got overheated or smth..

Exact code that i used:
Code: [Select]
#include <stm32f0xx.h> //stm32f030f4
#include "stm32f0xx_rcc.h" //we use rcc
#include "stm32f0xx_gpio.h"


//connection
#define LED_PORT GPIOF
#define LED_A (1<<6)
#define LED_C (1<<7)

void SystemCoreClockHSIPLL2(uint32_t RCC_PLLMul_x) {
RCC_DeInit(); //reset rcc
RCC_PLLCmd(DISABLE); //disable PLL
RCC_HSICmd(ENABLE); //enable hsi;
RCC_HCLKConfig(RCC_SYSCLK_Div1); //set sysclk divider
//RCC_PCLK1Config(RCC_HCLK_Div1); //set pclk1/2 dividers
//RCC_PCLK2Config(RCC_HCLK_Div1);
/**

* @brief  Configures the PLL clock source and multiplication factor.
* @note   This function must be used only when the PLL is disabled.
*
* @param  RCC_PLLSource: specifies the PLL entry clock source.
*          This parameter can be one of the following values:
*            @arg RCC_PLLSource_HSI_Div2: HSI oscillator clock selected as PLL clock source
*            @arg RCC_PLLSource_PREDIV1: PREDIV1 clock selected as PLL clock entry
*            @arg RCC_PLLSource_HSI48 HSI48 oscillator clock selected as PLL clock source, applicable only for STM32F072 devices
*            @arg RCC_PLLSource_HSI: HSI clock selected as PLL clock entry, applicable only for STM32F072 devices
* @note   The minimum input clock frequency for PLL is 2 MHz (when using HSE as
*         PLL source).
*
* @param  RCC_PLLMul: specifies the PLL multiplication factor, which drive the PLLVCO clock
*          This parameter can be RCC_PLLMul_x where x:[2,16]
*
* @retval None
*/
RCC_PLLConfig(RCC_CFGR_PLLSRC_HSI_Div2, RCC_PLLMul_x); //configure pll / divider. _x=[2..16]
RCC_PLLCmd(ENABLE); //enable pll
while (RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET) continue; //wait for pll to be ready
RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK); //set pll as sysclk
while (RCC_GetSYSCLKSource() != RCC_CFGR_SWS_PLL/*0x08*/) continue; //wait for PLL to be ready

SystemCoreClockUpdate(); //update SystemCoreClock
}

//delays some
void delay(uint32_t dly) {
while (dly--) asm("NOP");
}

int main(void) {
SystemCoreClockHSIPLL2(RCC_PLLMul_12); //go to 48Mhz
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOF, ENABLE);
GPIO_InitTypeDef gis;
gis.GPIO_Mode = GPIO_Mode_OUT;
gis.GPIO_OType = GPIO_OType_PP;
gis.GPIO_Pin = LED_A | LED_C;
gis.GPIO_PuPd = GPIO_PuPd_NOPULL;
gis.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(LED_PORT,&gis);
LED_PORT->ODR &= ~(LED_A | LED_C);

while(1) {
LED_PORT->ODR ^= (LED_A | LED_C);
delay(100000);
    }
}
Title: Re: STM32, ghetto style
Post by: dannyf on November 03, 2014, 12:30:36 am
You will need to route clock to the led port, and one of the two pins should be set and the other cleared - unless you used a probe on the pins.

If you don't have the led connected, you should check the value of SystemCoreClock while stepping through the code.

To see if the chip is damaged, you can simply boot up to main() and just flip the pins - commenting out the PLL portion of the code. If it doesn't run, the issue is somewhere else.
Title: Re: STM32, ghetto style
Post by: Ribster on November 03, 2014, 09:25:58 pm
Small update: Just tested the code on an STM32F051 discovery board and it does work as expected.
I'm going to desolder the sucker, i'm not trusting this. Thanks everybody for the help so far. I've learned a lot in the process.
And sorry for hijacking your thread, but i thought it was relevant and knew you could help me ;).

Greetings
Title: Re: STM32, ghetto style
Post by: Ribster on November 04, 2014, 05:51:01 pm
I'm using CooCox now. Fully on Windows. When i program my board to use your code it only works when i use a multiplier of 2.
So i only can enable the PLL when my systemclock frequency is 8MHz.
Just plain STM32F051, standard project with GPIO and RCC resource.
I'm really scratching my head here, i'm lost. The moment i select a PLL multiplier >2, the chip resets when i enable the PLL..

Greetings
Title: Re: STM32, ghetto style
Post by: westfw on November 04, 2014, 07:13:37 pm
Quote
the chip resets when i enable the PLL..
Can you implement individual  fault handlers, and figure out WHY it's resetting (and exactly where)?
Title: Re: STM32, ghetto style
Post by: dannyf on November 04, 2014, 07:54:27 pm
Not having the particular chip, I can only offer limited help.

the f0 chips share the same clock module so what works for a f03 should work for a f05.

second, those chips don't reset as traditional 8 bitters. So when you say that the chip resets, what exactly does it mean? After the -reset-, where is the execution at?

what exactly is the code you are running? Did you make changes to the start up files? How about preprocessor macros? ...

it is best to be more specific.
Title: Re: STM32, ghetto style
Post by: Koepi on November 04, 2014, 08:12:26 pm
If the code works again on your f051-disco, the problem source should be clear.
Also, I read somewhere that current Coocox is buggy. a few versions back and the functions work as expected. You should either try that, or setup your own Eclipse environment with gnu-arm-eabi compilers and STM plug-ins. Then you can use the STM standard peripheral lib in the last version, which should work flawless.
_Or_ you could open an own thread, as this is again and continuesly quite off-topic for STM32 ghetto style and a way more concrete problem with non-ghetto STM ;)
Title: Re: STM32, ghetto style
Post by: Ribster on November 04, 2014, 10:25:26 pm
Hey guys,

Thanks for helping me out.

This is the code i'm using for the F0 discovery:
Code: [Select]
#include <stm32f0xx.h> //stm32f030f4
#include "stm32f0xx_rcc.h" //we use rcc
#include "stm32f0xx_gpio.h"
#include "stm32f0xx_flash.h"

//connection
#define LED_PORT GPIOC
#define LED_A (1<<8)
#define LED_C (1<<9)

void SystemCoreClockHSIPLL2(uint32_t RCC_PLLMul_x) {
RCC_DeInit(); //reset rcc
RCC_PLLCmd(DISABLE); //disable PLL
RCC_HSICmd(ENABLE); //enable hsi;
RCC_HCLKConfig(RCC_SYSCLK_Div1); //set sysclk divider
//RCC_PCLK1Config(RCC_HCLK_Div1); //set pclk1/2 dividers
//RCC_PCLK2Config(RCC_HCLK_Div1);
/**

* @brief  Configures the PLL clock source and multiplication factor.
* @note   This function must be used only when the PLL is disabled.
*
* @param  RCC_PLLSource: specifies the PLL entry clock source.
*          This parameter can be one of the following values:
*            @arg RCC_PLLSource_HSI_Div2: HSI oscillator clock selected as PLL clock source
*            @arg RCC_PLLSource_PREDIV1: PREDIV1 clock selected as PLL clock entry
*            @arg RCC_PLLSource_HSI48 HSI48 oscillator clock selected as PLL clock source, applicable only for STM32F072 devices
*            @arg RCC_PLLSource_HSI: HSI clock selected as PLL clock entry, applicable only for STM32F072 devices
* @note   The minimum input clock frequency for PLL is 2 MHz (when using HSE as
*         PLL source).
*
* @param  RCC_PLLMul: specifies the PLL multiplication factor, which drive the PLLVCO clock
*          This parameter can be RCC_PLLMul_x where x:[2,16]
*
* @retval None
*/
FLASH_SetLatency(FLASH_Latency_1);
FLASH_PrefetchBufferCmd(ENABLE);
RCC_PLLConfig(RCC_CFGR_PLLSRC_HSI_Div2, RCC_PLLMul_x); //configure pll / divider. _x=[2..16]
RCC_PLLCmd(ENABLE); //enable pll
while (RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET) continue; //wait for pll to be ready
RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK); //set pll as sysclk
while (RCC_GetSYSCLKSource() != RCC_CFGR_SWS_PLL/*0x08*/) continue; //wait for PLL to be ready

SystemCoreClockUpdate(); //update SystemCoreClock
}

//delays some
void delay(uint32_t dly) {
while (dly--) __asm("NOP");
}

int main(void) {
SystemCoreClockHSIPLL2(RCC_PLLMul_12); //go to 48Mhz

RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOC, ENABLE);
GPIO_InitTypeDef gis;
gis.GPIO_Mode = GPIO_Mode_OUT;
gis.GPIO_OType = GPIO_OType_PP;
gis.GPIO_Pin = LED_A | LED_C;
gis.GPIO_PuPd = GPIO_PuPd_NOPULL;
gis.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(LED_PORT,&gis);
LED_PORT->ODR &= ~(LED_A);
LED_PORT->ODR |= (LED_C);

while(1) {
LED_PORT->ODR ^= (LED_A | LED_C);
delay(1000000);
    }
}

The code for my board differs only in led pins.
When i set the multiplier at 2 and at 12, the discovery board shows remarkable difference in toggling speed.

On my custom board, when i use the multiplier of 2, the leds toggle and everything works on 8MHz (as per SystemClock on debug)
When i use the multiplier of 3, it gives me 12MHz.

When i look at the SystemCoreClockUpdate() routine on my custom board, RCC->CFGR & RCC_CFGR_SWS does not give me 0x08. So PLL isn't used as system clock.
This is only when the multiplier is 2 or 3, else it resets and i cannot debug the chip.
The moment i use a multiplier of 4 and up, the chip does nothing and attached you can see the nRST pin.. So it cycles the reset line.
The schematic in attachment also.

Greetings
Title: Re: STM32, ghetto style
Post by: Ribster on November 04, 2014, 10:34:17 pm
If the code works again on your f051-disco, the problem source should be clear.
Also, I read somewhere that current Coocox is buggy. a few versions back and the functions work as expected. You should either try that, or setup your own Eclipse environment with gnu-arm-eabi compilers and STM plug-ins. Then you can use the STM standard peripheral lib in the last version, which should work flawless.
_Or_ you could open an own thread, as this is again and continuesly quite off-topic for STM32 ghetto style and a way more concrete problem with non-ghetto STM ;)

Hey, i have no problems with creating a new topic. Just say it if i'm pushing this thread :), i know i'm on a thin line here :p..
Thought it was a simple problem, but apparently it's bigger then i thought.
I'm supprised that i am having this problems on the F051. No one ever had these kind of problems with the ghetto f030 ?
Title: Re: STM32, ghetto style
Post by: dannyf on November 04, 2014, 11:22:03 pm
The discovery and the custom board use the same chip? If so the code is working and there is something unique about the custom board.

btw, there is no mechanism I know of where the chip will reset itself by pulling the reset line. This is interesting.

you said you cannot debug? What are you using for debugging?
Title: Re: STM32, ghetto style
Post by: Ribster on November 04, 2014, 11:42:50 pm
No, i use the 48pin LQFP and the discovery uses the 64 pin.
My code works for both though.
I've read somewhere that some faults pull down the reset line, so that's why i checked for it.

When i step through my code when the configuration is set to multiplier >3, the moment i execute "RCC->CR |= RCC_CR_PLLON;" i lose connection to the chip.
At that moment my chip resets.
Title: Re: STM32, ghetto style
Post by: dannyf on November 05, 2014, 12:44:34 am
I ran your code, with minor changed to output on different pins, on my stm32f030 and it worked as expected.

Quote
I've read somewhere that some faults pull down the reset line,

You are right about that. It is stated in the reset and clock control section. and the reset state is output to the RESET pin.

Something weird is happening here.
Title: Re: STM32, ghetto style
Post by: dannyf on November 05, 2014, 01:47:26 am
Furthermore, I simulated it in keil on stm32f051r8, and it worked just as expected.

I think the issue is hardware related for your custom board. Maybe decoupling? cross soldering? wrong wiring?....
Title: Re: STM32, ghetto style
Post by: Ribster on November 05, 2014, 11:57:14 pm
Okay, you guys are gonna kill me for this..
VDDA wasn't connected on my board...
The good news is, i will shut up now because it's solved :).
Thanks for the support  :-+
Title: Re: STM32, ghetto style
Post by: dannyf on November 06, 2014, 12:11:49 am
Progress!

Title: Re: STM32, ghetto style
Post by: Ribster on November 06, 2014, 12:46:42 am
Yes it is!
Problems are really the best way to learn the internals of a microcontroller.
On to the next problem :p
Title: Re: STM32, ghetto style
Post by: Koepi on November 07, 2014, 06:14:15 am
Ok, first of two boost ICs arrived today, NCP1402 (http://www.onsemi.com/pub/Collateral/NCP1402-D.PDF). This will allow to feed the STM32F030 with a single alkaline battery.
Unfortunately, the inductors and Schottky diodes didn't arrive yet. I could improvise with 1N4148, but I don't dare to wick a coil "somehow" and hope that it swings sufficiently.
I'm also still waiting for the BL8530 (http://www.belling.com.cn/2011p/BL8530_en.pdf) step-ups which are significantly cheaper.

I think I need to extend the test to efficiency at standard conditions as well (fresh charges battery, measure voltage and current on the input side and then again on the output side for starters). That hopefully is helpful for deciding which buck or boost circuit to choose for using these tiny and mighty µCs in mobile applications.
Title: Re: STM32, ghetto style
Post by: dannyf on November 07, 2014, 01:29:17 pm
ON makes quite a few of those LED drivers that can function as regulators (both up and/or down).

With a small load, a small coil (the datasheet says 47uh) + 1n4148 should work.
Title: Re: STM32, ghetto style
Post by: Koepi on November 07, 2014, 03:28:43 pm
50 pieces of CD54 47µH are somewhere between China Mainland and Germany, finding their way to my hands :D

Interesting hint with those ON semi LED drivers. Will look around a little. For my taste that is an interesting shootout between different power supply variants for our µCs. :)
Title: Re: STM32, ghetto style
Post by: dannyf on November 07, 2014, 03:55:24 pm
Agreed.

However, the type of regulators to go may be highly application specific. For example, smps wins hands down for high current, high voltage drop applications, because of their efficiency. However, for low-power, sleep-dominated applications, low-quiescent current ldos may be better as smps becomes incredibly inefficient in those cases.

That's where some unique topologies may be interesting to try, like the ON chip you picked, or the gated oscillator types.
Title: Re: STM32, ghetto style
Post by: Koepi on November 07, 2014, 07:48:33 pm
Started to think about a measurement scenario and decided to first take my µC 4-digit-7-segment LED clock which is fed by a LiIon battery and stableized with the LDO. This really seems to show the efficiency while I'm not yet sure how to calculate it correctly - simply the ratio of A in versus A out?

Killed the 400mA fuse of my multimeter during the test; had a 500mA one in an old, unused multimeter which I replaced the broken fuse with now. Had to start all over to make sure the values are comparable.

I'll start with the table and play around with the numbers a little, adding the efficiency as Wattage in/out ratio.

Vin was 3,901V from the LiIon battery.

LDOVoutmAinmAoutNoLoad µAmWinmWoutEff %
MCP1700 (http://ww1.microchip.com/downloads/en/DeviceDoc/20001826C.pdf)3.2831.891.881.37,376,1783,71
PAM3101 (http://www.diodes.com/datasheets/PAM3101.pdf)3.3031.961.8857.67,656,2181,21
MCP1825S (http://ww1.microchip.com/downloads/en/devicedoc/22056b.pdf)3.3341.971.9344.07,686,4383,73
RT9166 (http://www.100y.com.tw/pdf_file/38-Richtek-RT9166.pdf)3.2601.871.866.17,296,0683,12

As comparison, using the battery directly to feed the clock results in a 2.41mA load, which are 9,40mW. It is more efficient to use a LDO?!
Title: Re: STM32, ghetto style
Post by: dannyf on November 07, 2014, 08:04:44 pm
Quote
simply the ratio of A in versus A out?

Technically yes but practically, that measurement is not as meaningful.

A more "efficient" regulator, particularly a ldo, is one that can work with minimum drop-out voltage and has the least idle current. So if you will, a voltage efficiency would be Vout / minimum Vin (not Vout / Vin), and a current efficiency would be Iout / Iin.

The issue with your measurements is that with sufficiently high Vin - Vout, they all look equally "efficient" - the power inefficiencies are really caused by the voltage drop (which is the same for all regulators, until Vin is sufficiently close to Vout).

To me, if you care about efficiency, you are likely in a low-power application and for a ldo, the current efficiency is much more important. Voltage efficiency is important when battery life is considered.
Title: Re: STM32, ghetto style
Post by: Koepi on November 07, 2014, 09:00:29 pm
You are right, as you can see in the mA(in) of the MCP1700 and RT9166 - they consume the least power for driving the clock. Interestingly, the RT9166 looks even more efficient as the Wattage-ratio suggests compared with the MCP1700.

Hopefully tomorrow morning the 47µH coils are in the post so I can start with fiddling with boosters :)

Edit: Ah, the reason for using a LDO instead of battery directly leading to a better energy usage is that the resistors and LEDs pull more current at higher voltage.
Title: Re: STM32, ghetto style
Post by: Koepi on November 08, 2014, 10:54:28 am
Lucky me, the coils arrived!

Built the NCP1402 to the sample from it's datasheet, only replaced the diode by a 1N4148 as the SS14 are still on their way. I was thrilled whether this could work at all - but it does! The efficiency sure suffers, but for the first test I think it's great! The self-built ghetto circuit has only 1/3rd the size of a PCB you can buy!

I used a STM32F030 dimming an LED as load now, so I have two load peaks which show a bigger bandwidth. This tiny bugger drives the µC with a single everyday AA battery! :)
Title: Re: STM32, ghetto style
Post by: dannyf on November 08, 2014, 12:54:49 pm
The efficiency would go up with a schottky diode for sure. However, it follows the general observation that smps has lower efficiency at lower load conditions. That makes them less desirable at battery-powered and low load) applications - cell phones are different.

Have you tried lt1073? It is one of those gated oscillator types - it stops working when the output has reached the desired output levels. Quite pricey, however.
Title: Re: STM32, ghetto style
Post by: Koepi on November 08, 2014, 01:52:58 pm
I keep looking around for other ways to get power to the µC as well. I even thought about the most ghetto variant - a Joule Thief :D But that is way too inefficient and wouldn't deliver stable output for higher loads like for example 100mA.

I was looking into charge pumps as well, but those are quite expensive ...

Cheapest offers I could find for the  LT1073 (http://cds.linear.com/docs/en/datasheet/1073fa.pdf):
http://www.aliexpress.com/item/32214105960.html (http://www.aliexpress.com/item/32214105960.html)
http://www.aliexpress.com/item/LT1073/2011254186.html (http://www.aliexpress.com/item/LT1073/2011254186.html)

just like the TPS60302 (http://pdf.datasheetcatalog.com/datasheet/texasinstruments/tps60302.pdf) charge pumps:
http://www.aliexpress.com/item/1798864746.html (http://www.aliexpress.com/item/1798864746.html)

They share the little possible load of about <=20mA, though.
Title: Re: STM32, ghetto style
Post by: Kjelt on November 08, 2014, 01:57:48 pm
Cheapest offers I could find for the  LT1073 (http://cds.linear.com/docs/en/datasheet/1073fa.pdf):
http://www.aliexpress.com/item/LT1073/2011254186.html (http://www.aliexpress.com/item/LT1073/2011254186.html)
I would not trust such an offer. An ic that regularly would cost $4 /100 pcs now for $1  that smells..... Could be excess stock but I had my share with fake chips.
Title: Re: STM32, ghetto style
Post by: dannyf on November 08, 2014, 02:08:20 pm
100ma would need a real amps. Converters like lt1073 are only useful for low power applications, unfortunately.
Title: Re: STM32, ghetto style
Post by: dannyf on November 11, 2014, 02:14:02 pm
Nothing new but in case you are wondering, you can indeed download stm8s003 binaries into stm8s103 and run flawlessly, or download stm8s103 binaries into stm8s003 and run flawlessly.

That's useful because at this moment, stm8s103f3 is actually cheaper than stm8s003f3 - the two chips are identical except for a couple minor differences in spec (no differences in the actual chips that I have examined).

Title: Re: STM32, ghetto style
Post by: Koepi on November 12, 2014, 05:53:51 am
Great observation! I would expect that a .hex works for the the same family of µCs (like stm32f103<xxx>, stm32f407<xxx>), but depends of course on the peripherals feature set. Should try some more variants like F030->F051; that's where I think problems could arise (at least if you use a binary for the bigger µC on the smaller one). For the ARM based µCs, ST has an AppNote (AN3364) which explains the compatibility a bit: http://www.st.com/web/en/resource/technical/document/application_note/DM00024853.pdf (http://www.st.com/web/en/resource/technical/document/application_note/DM00024853.pdf)

Good news here as well, TI shipped some ICs on monday which are already close to my place now and should arrive today :)
Monday: 11:45 am   Picked up      GRAND FORKS, ND
Tuesday: 5:24 am   Departed FedEx location      MEMPHIS, TN
8:08 pm   Arrived at FedEx location      ROISSY CHARLES DE GAULLE CEDEX FR
9:33 pm   International shipment release - Import      COLOGNE DE
Wednesday: 4:05 am   Arrived at FedEx location      HANNOVER DE
... which is ~100km from here and thus should get delivered soon.

These parts are in the envelope:
TPS60302 (http://www.ti.com/product/tps60302) - Single-Cell to 3.0V/3.3V, 20mA Dual Output, High Efficiency Charge Pump
TPS60200 (http://www.ti.com/product/tps60200) - Regulated 3.3-V Low Ripple Charge Pump With Low Battery Indicator
TPS61097A-33 (http://www.ti.com/product/tps61097a-33) - 0.9Vin, 3.3Vout Boost Converter with Bypass Switch - 5nA Shutdown Current
TLV61225 (http://www.ti.com/product/tlv61225) - Single Cell High Efficient Step-Up Converter in 6 pin SC-70 Package

I think they are a good choice to also compare different technologies for buck and/or boost.
Title: Re: STM32, ghetto style
Post by: dannyf on November 12, 2014, 12:04:58 pm
Within the S-series, binary compatability should be very good - they use the same header file so register locations must be the same.

There are, however, two L families, L10x and L15x, I think.

Quote
F030->F051; that's where I think problems could arise (at least if you use a binary for the bigger µC on the smaller one).

They should be identical (other than the perpherals) - the same header file is used for those chips.

On the TI parts, look like they have done a good job sending them to you. Charge pumps tend to be more efficient but not as capable current-wise as a real dc/dc converter.
Title: Re: STM32, ghetto style
Post by: Koepi on November 12, 2014, 07:51:06 pm
Built up a step-up from TI now - man, it's so tiny! Especially with the Murata coil/inductor; only half the size of my NCP1402 board!
Tested it with the STM32F030 in SoftPWM LED dimming. I replaced the 400mA fuse with a new one in the multimeter and had the issue that the board won't start up in the 400mA fuse mode; it does in the 10A mode with less precision in the measurement though. It is more efficient as it doesn't use a wrong diode like my NCP-pcb.
The huge no-load-current is alarming, seems something is wrong there; the input voltage of 1.25V from the battery drops to 0.7-0.9V when using the 400mA-fuse; with the 10A fuse, no load can be measured. (This seems correct. When using a 500mA fuse, the drain goes up to 160mA and the capacitors start whining with high frequency. Must be part of this circuit/IC that it can't be measured this way. Might be some voltage drop over a diode, for example. 0.3-0.5V sound like that.)

Vin was 1,25V from the alcaline battery.

Step-upVoutmAinmAoutNoLoad µAmWinmWoutEff %
NCP1402 (http://www.onsemi.com/pub/Collateral/NCP1402-D.PDF)3.32751618.593.7553.1256.66
(1N4148)3.321002518.5125.0083.0066.40
TPS61097A-33 (http://www.ti.com/lit/ds/symlink/tps61097a-33.pdf)3.285816~0mA72.5052.4872.39
3.288525~0mA106.2582.0077.18



For comparison, the LDO-table again:
Vin was 3,901V from the LiIon battery.

LDOVoutmAinmAoutNoLoad µAmWinmWoutEff %
MCP1700 (http://ww1.microchip.com/downloads/en/DeviceDoc/20001826C.pdf)3.2831.891.881.37,376,1783,71
PAM3101 (http://www.diodes.com/datasheets/PAM3101.pdf)3.3031.961.8857.67,656,2181,21
MCP1825S (http://ww1.microchip.com/downloads/en/devicedoc/22056b.pdf)3.3341.971.9344.07,686,4383,73
RT9166 (http://www.100y.com.tw/pdf_file/38-Richtek-RT9166.pdf)3.2601.871.866.17,296,0683,12

As comparison, using the battery directly to feed the clock results in a 2.41mA load, which are 9,40mW. It is more efficient to use a LDO as the 7-segment drains less current with less voltage supplied.
Title: Re: STM32, ghetto style
Post by: dannyf on November 12, 2014, 10:50:02 pm
I read it to mean two things:

1) under comparable load (the same Iout), the TI charge pump is more efficient than the ON semi dc/dc converter - no surprise there;
2) between the smps regulators and the ldos (under different but light load conditions, however), the ldos are more efficient than smps - no surprise there too.

The most efficient way would be to go ldo-less - when you need a reference, use the onboard Vref generator or external Vref.
Title: Re: STM32, ghetto style
Post by: Koepi on November 14, 2014, 02:00:01 pm
Oh, that was a classic "step up" above. Yesterday evening I built a charge pump, finally. Since they are MSOP10 they are quite hard to handle without adapter board. Which is why I deliver measurements now, I had to fix the connections again and finally managed to get it running a few moments ago. ;)


Vin was 1,25V from the alkaline battery.

Charge pumpVoutmAinmAoutNoLoad µAmWinmWoutEff %
TPS60302 (http://www.ti.com/lit/ds/symlink/tps60302.pdf)3.3571173388.7556.9364.15
3.35922433115.0080.3869,89

Since those 24mA out are already beyond the load recommended in the datasheet, the efficiency looks bad in this example. In real-world it should work a bit better. 20mA is very little load, though.
Title: Re: STM32, ghetto style
Post by: dannyf on November 14, 2014, 03:53:24 pm
That's tiny. Your soldering skills are infinitely better than mine.
Title: Re: STM32, ghetto style
Post by: dannyf on November 15, 2014, 02:03:07 pm
I am not reverting to an old version of EWSTM8 that supports only STM8S103F to develop code for STM8S003F. No problem whatsoever in debugging and execution.
Title: Re: STM32, ghetto style
Post by: Koepi on November 15, 2014, 02:28:09 pm
Too bad the STM8 support is so Windows centric. I have three nice STM8 boards around, but fail to get a guide to setup Eclipse/SDCC (which supports STM8 - allegedly) on Mac. Which is my usual work space now. If that support would be better I'm sure it would be easy to hype and use STM8 more.
Title: Re: STM32, ghetto style
Post by: dannyf on November 15, 2014, 02:34:17 pm
So true.

The future is STM8 is uncertain, given the CM0/CM0+ competition.
Title: Re: STM32, ghetto style
Post by: dannyf on November 15, 2014, 06:40:57 pm
Quote
fail to get a guide to setup Eclipse/SDCC (which supports STM8 - allegedly)

I can confirm that SDCC does indeed support STM8S, with some modifications to the header / source files. I could get it to compile (my code + st's library) and link to produce a .hex file.

Two issues:

1) the compile time is horrendous: stm8s_tim1.c for example takes 30 - 60 seconds to compile. That's like forever;
2) more importantly, the produced code is huge: a simple blinky yields a .hex file of almost 60k. Maybe there is a switch to trim unused code sections.

This is for SDCC + CB.
Title: Re: STM32, ghetto style
Post by: Koepi on November 15, 2014, 07:35:22 pm
Thanks for testing that, dannyf! Also for verifying that it really works.

Did you see
http://sdcc.sourceforge.net/mediawiki/index.php/Stm8_code_size (http://sdcc.sourceforge.net/mediawiki/index.php/Stm8_code_size) ?
As compiler options, setting
--opt-code-size --max-allocs-per-node 10000000

should shrink the binary significantly.
Title: Re: STM32, ghetto style
Post by: dannyf on November 15, 2014, 08:55:05 pm
I already had the code size flagged but adding the 2nd flag made no difference.

The code size comparison quoted is both fair and unfair.

It is fair in that it is an accurate description of how each compiler translated a piece of C code into executable.

It is unfair in that that's not how most people code: we often have large number of modules in a few files. You would include those modules in your project but you may not use every function in every module included. Instead, you rely on the compiler / linker to not link in the unused modules, significantly shrinking the size of the executable.

SDCC does not have the ability to trim unused code - stunning in this time and age, if you ask me. So the only solution is for you to only include those functions in your project.

Or use really really big chips to contain the code that you don't use, :)
Title: Re: STM32, ghetto style
Post by: true on November 15, 2014, 09:02:12 pm
SDCC does not have the ability to trim unused code - stunning in this time and age, if you ask me. So the only solution is for you to only include those functions in your project.

Yes, this is a serious omission of the linker. Compiler quality is sub-par but usable but the linker is just terrible.

There are some workarounds of putting common code into libraries but it's really a total PITA. This optimization is something any modern linker (especially one for small platforms like SDCC) should be taking care of already.
Title: Re: STM32, ghetto style
Post by: westfw on November 16, 2014, 04:21:42 am
Quote
Code: [Select]
        RCC_DeInit(); //reset rcc
RCC_PLLCmd(DISABLE); //disable PLL
RCC_HSICmd(ENABLE); //enable hsi;
RCC_HCLKConfig(RCC_SYSCLK_Div1); //set sysclk divider
RCC_PLLConfig(RCC_CFGR_PLLSRC_HSI_Div2, RCC_PLLMul_12); //configure pll / divider. _x=[2..16]
RCC_PLLCmd(ENABLE); //enable pll
while (RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET) continue; //wait for pll to be ready
RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK); //set pll as sysclk
while (RCC_GetSYSCLKSource() != RCC_CFGR_SWS_PLL/*0x08*/) continue; //wait for PLL to be ready

SystemCoreClockUpdate();
This is the sort of vendor library code that I really dislike.   All that to set up the clock; a feature that most programmers really don't care that much about at the detailed level.  You should be able to say "my crystal is xxx and I want the cpu to run at yyy", and there should be a function that goes off and DOES that without worrying about PLL inputs and multipliers and such.  And it should generate pretty minimal code; not dragging in a lot of libraries.
So I wrote such a function:  SimpleClockInit(long desiredcpuspeed, long xtalspeed), in the way I think such functions should be written.  It's verbose, but inline.  If given a reasonable compiler and constant arguments, it optimizes to relatively minimal code.  It generates information useful for debugging its own operation.

For example, here's the code that it generates if you tell it you want 8MHz with no crystal:
Code: [Select]
00000000 <main>:
   0: e7fe      b.n 0 <main>
   2: bf00      nop
(you're right; there is nothing there.  Because operation off of the 8MHz internal clock is the default state.)

Here's the more inclusive code for getting 72MHz from an 8MHz crystal:
Code: [Select]
Crystal: 8000000, Desired: 72000000

00000000 <main>:
   0: bf00      nop

00000002 <PICK_HSE>:
   2: bf00      nop

00000004 <HSE_ON>:
   4: 4b12      ldr r3, [pc, #72] ; (50 <Clock_done+0x2>)
   6: 681a      ldr r2, [r3, #0]
   8: 4619      mov r1, r3
   a: f442 3280 orr.w r2, r2, #65536 ; 0x10000
   e: 601a      str r2, [r3, #0]
  10: 680a      ldr r2, [r1, #0]
  12: 4b0f      ldr r3, [pc, #60] ; (50 <Clock_done+0x2>)
  14: 0390      lsls r0, r2, #14
  16: d5fb      bpl.n 10 <HSE_ON+0xc>

00000018 <Latency2>:
  18: 4a0e      ldr r2, [pc, #56] ; (54 <Clock_done+0x6>)
  1a: 6811      ldr r1, [r2, #0]
  1c: f041 0102 orr.w r1, r1, #2
  20: 6011      str r1, [r2, #0]
  22: 685a      ldr r2, [r3, #4]
  24: f442 6280 orr.w r2, r2, #1024 ; 0x400
  28: 605a      str r2, [r3, #4]

0000002a <PLL_9>:
  2a: 685a      ldr r2, [r3, #4]
  2c: f442 12e8 orr.w r2, r2, #1900544 ; 0x1d0000
  30: f042 0202 orr.w r2, r2, #2
  34: 605a      str r2, [r3, #4]

00000036 <PLL_CR>:
  36: 681a      ldr r2, [r3, #0]
  38: f042 7280 orr.w r2, r2, #16777216 ; 0x1000000
  3c: 601a      str r2, [r3, #0]

0000003e <PLL_SPIN>:
  3e: 6819      ldr r1, [r3, #0]
  40: 4a03      ldr r2, [pc, #12] ; (50 <Clock_done+0x2>)
  42: 0189      lsls r1, r1, #6
  44: d5fb      bpl.n 3e <PLL_SPIN>

00000046 <USE_PLL>:
  46: 6853      ldr r3, [r2, #4]
  48: f043 0302 orr.w r3, r3, #2
  4c: 6053      str r3, [r2, #4]

0000004e <Clock_done>:
  4e: e7fe      b.n 4e <Clock_done>
  50: 40021000 .word 0x40021000
  54: 40022000 .word 0x40022000
(The nop's are for testing purposes, so that the generated labels actually show up in the disassembly.)

(detailed study will reveal that the compiler is NOT doing a great job of optimization (at least, it looks that way.)  There are constants being unnecessarily being re-loaded into registers, inside of loops, for example.  But it's a lot less code than using the ST peripheral library...)
Title: Re: STM32, ghetto style
Post by: Kjelt on November 16, 2014, 10:00:12 am
This is the sort of vendor library code that I really dislike.
Well AFAIAC this maps directly on the datasheet/ ref. manual and allows all the flexibility that may be required by a user, such as dynamic clock alterations for some functions, PLL changes etc.
It also easily allows you to write higher level functions (as you did demonstrate) so to say put another abstraction layer on top of it.
I don,t see the harm. It supports both ways, if they only would have supplied the higher abstraction level functions than a lot more people would be dissatisfied i think.
Title: Re: STM32, ghetto style
Post by: Kjelt on November 16, 2014, 10:03:01 am
@Koepi : great job! I do see the normal smps efficiencies of around 80+% as expected but what would it take to get to 90%?
Higher switching frequencies?
Title: Re: STM32, ghetto style
Post by: dannyf on November 16, 2014, 01:09:00 pm
Quote
This optimization is something any modern linker (especially one for small platforms like SDCC) should be taking care of already.

Agreed. It basically renders the compiler not usable for small devices.
Title: Re: STM32, ghetto style
Post by: dannyf on November 16, 2014, 08:22:08 pm
Quote
It basically renders the compiler not usable for small devices.

Having said that, this thing does work (at least in blinking an led).

I can write a step-by-step tutorial if anyone is interested.
Title: Re: STM32, ghetto style
Post by: paulie on November 17, 2014, 11:13:25 am
I would definitely like to see what you can come up with. Maybe another 21 step GUI procedure like the one earlier in this thread. For those who want to avoid some fuss here's a more streamlined approach:

https://www.eevblog.com/forum/microcontrollers/one-dollar-one-minute-arm-development/msg506113/?topicseen#msg506113 (https://www.eevblog.com/forum/microcontrollers/one-dollar-one-minute-arm-development/msg506113/?topicseen#msg506113)

Unzip and hit 'a'. Notice as usual the entire compiler and programming tools have been attached to the thread and not just linked. However I do think there might be something wrong if your setup takes 60 sec to compile. For me a timer1 demo takes only a fraction of a second to produce hex and maybe another sec to flash the chip. Of course that's CLI which is not very popular with the mainstream community.

It's true this compiler does not hold a candle up to commercial deals like IAR or Keil or even GCC which has had hundreds of top experts working on it for many years. If you review the history it's basically a one man show and fairly recent effort. It's more like comparing Turbo-c with MS Visual and C# compilers. In fact SDCC feels and performs very similar to that old Borland standby. I really like Turbo-C for PC programming and SDCC is one of my favorite MCU utilities.

BTW thanks again for bringing these great chips to my attention and, even if nobody else seems to appreciate these STM8 parts, I personally would be very interested to see what you can come up with for another tutorial.
Title: Re: STM32, ghetto style
Post by: dannyf on December 07, 2014, 07:45:37 pm
Quote
I think those 003s are actually 103s marked down.

I can confirm that 003 binaries can be flashed to 103s and run flawlessly; and 103 binaries can be flashed to 003s and run flawlessly.
Title: Re: STM32, ghetto style
Post by: Koepi on January 14, 2015, 06:54:25 pm
I ordered PCBs for STM32F030 boards from JM Electron and they arrived today. My solder iron tip from the new soldering and hot fan station is a bit big compared to my previous Ersa tip, so it was a bit complicated to build it up. (I ordered a set of different tips and some smaller ones now.)

What is different to the ghetto style version? Well, it has a mini USB plug for feeding it directly with power. A LDO (XC6202 (http://www.torex.co.jp/english/products/voltage_regulators/data/XC6206.pdf)) delivers the needed 3.3V, up to 200mA. A reset switch is prepared, a power LED and a user LED which can be disconnected from PA1 via jumper; also a Boot0-jumper is on there. UART and SWD have additional pins so periphery can stay plugged in while uploading a new firmware. Useful are two additional GND, 5V and 3.3V pins. Also, an external oscillator can be soldered in.

But all in all it isn't far better then our ghetto style version. At least for my taste.

(Yes, I know - I didn't think while soldering the pin headers, so the UART/SWD pin headers are on the bottom, too :D They belong to the top for better accessability.)

Edit: Jeez. Just took a closer look at the XC6202 datasheet. It needs 1µF capacitors, those are placed directly left and right from the IC (which is very close and the good part of the design). Replaced them now with correct capacitors. Vdda is not filtered with a ferrite bead, but has a 0R bridge. Will replace it with a ferrite, too. The BOM from the PCB is a bit of a mess. Room for improvements at least! :)
Title: Re: STM32, ghetto style
Post by: dannyf on January 14, 2015, 11:06:17 pm
Nice work, :)

Maybe you can sell them to the chinese cloners.
Title: Re: STM32, ghetto style
Post by: trimarco232 on January 26, 2015, 05:49:07 pm
Hi all,
I owned this one on taobao, not realy ghetto style, but I love mounting holes and am too lazy to solder, the price should be less than 2$.
Some thoughts :
I have CooCox and a cheap jlink debugger. If I use the on board crystal too, only 10 IOs will remain for use
They are only 2 gnd pins on the whole board, one on the SWD header and one on the uart header
If you use jlink for the first time in the session, you will be asked to select the device manually. Press the "yes" button, then select "ST", then select "STM32F030F4"

Here is some code that works:

Code: [Select]
/* STM32F030F4P6 chinese board application
 * slave for Single-wire half-duplex communication
 * waits for the master's request, then
 * - converts the corresponding adc channel
 * - reads the corresponding io pin
 * - put the results into a byte and send the byte while setting an rs485 driver output enable
 *
 *
 */



#include <stdio.h>
#include <stm32f0xx.h>
#include <system_stm32f0xx.h>
#include <stm32f0xx_gpio.h>
#include <stm32f0xx_rcc.h>
#include <stm32f0xx_adc.h>
#include "stm32f0xx_misc.h"
#include "stm32f0xx_usart.h"


void adc_conv_s();
void gpio_init();
void adc_init ();
void usart_init();



volatile uint16_t user;
volatile uint16_t user1 = 110;
volatile uint8_t tab_speed[] = {0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,39,41,43,45,47,49,51,53,55,57,59,61,63,63,63,63,63,1,1,1,1};

volatile uint8_t usart_rx_d;
volatile uint8_t usart_tx_d;



int main (void) {
  gpio_init();
  adc_init ();
  usart_init();


  while (1) {

  }

}


void USART1_IRQHandler(void)
{
GPIOA->BRR = GPIO_Pin_10;  // Set PA10 Low -> rs485 Driver Output Disable
usart_tx_d = 128+64;
 if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)
  {
    /* Read one byte from the receive data register */
usart_rx_d = USART_ReceiveData(USART1);
switch (usart_rx_d) {
case 0x24:
ADC1->CHSELR = 1<<0;
if (GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_4)) {usart_tx_d = 128;}
adc_conv_s();
break;
case 0x25:
ADC1->CHSELR = 1<<1;
if (GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_5)) {usart_tx_d = 128;}
adc_conv_s();
break;
case 0x26:
ADC1->CHSELR = 1<<2;
if (GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_7)) {usart_tx_d = 128;}
adc_conv_s();
break;
case 0x27:
ADC1->CHSELR = 1<<3;
if (GPIO_ReadInputDataBit(GPIOB,GPIO_Pin_1)) {usart_tx_d = 128;}
adc_conv_s();
break; }
  }
}

void adc_conv_s()
{
ADC_StartOfConversion(ADC1);
while(!ADC_GetFlagStatus(ADC1, ADC_FLAG_ADEN)); /* Wait the ADCEN flag */ // why 2 times ?
GPIOA->BSRR = GPIO_Pin_10;  // Set PA10 HIGH -> rs485 Driver Output Enable
ADC_StartOfConversion(ADC1);
while(!ADC_GetFlagStatus(ADC1, ADC_FLAG_ADEN)); /* Wait the ADCEN flag */

usart_rx_d = ADC_GetConversionValue(ADC1);
usart_rx_d = tab_speed[usart_rx_d/2];
usart_tx_d += usart_rx_d;
USART_SendData(USART1, usart_tx_d );
}




void gpio_init(void) {
  GPIO_InitTypeDef GPIO_InitStructure;
  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA | RCC_AHBPeriph_GPIOB, ENABLE);

  GPIO_InitStructure.GPIO_Pin = (GPIO_Pin_4|GPIO_Pin_5|GPIO_Pin_7); // input BUTTON S1,S2,S3
  GPIO_InitStructure.GPIO_Speed=GPIO_Speed_2MHz;
  GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IN;
  GPIO_InitStructure.GPIO_PuPd=GPIO_PuPd_UP;
  GPIO_Init(GPIOA, &GPIO_InitStructure); // Initialises the GPIOA

  GPIO_InitStructure.GPIO_Pin = (GPIO_Pin_1); // input BUTTON 4
  GPIO_Init(GPIOB, &GPIO_InitStructure); // Initialises the GPIOB

}



void adc_init (void) {
  GPIO_InitTypeDef         GPIO_InitStructure;
  ADC_InitTypeDef          ADC_InitStructure;

  /* GPIOC Periph clock enable */
  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOC, ENABLE);

  /* ADC1 Periph clock enable */
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE);


  /* Configure ADC Channel0 to 3 as analog input */
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1 | GPIO_Pin_2 | GPIO_Pin_3 ;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AN;
  GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL ;
  GPIO_Init(GPIOA, &GPIO_InitStructure);

/* ADC1 Configuration *******************************************************/
  ADC_DeInit(ADC1);
  ADC_InitStructure.ADC_Resolution = ADC_Resolution_8b; /* Configure the ADC1 with a resolution equal to 8 bits*/
  ADC_InitStructure.ADC_ContinuousConvMode = DISABLE;
  ADC_InitStructure.ADC_ExternalTrigConv =  ADC_ExternalTrigConvEdge_None;
  ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
  ADC_InitStructure.ADC_ScanDirection = ADC_ScanDirection_Upward;
  ADC_Init(ADC1, &ADC_InitStructure);


  ADC_ChannelConfig(ADC1, ADC_Channel_0 , ADC_SampleTime_239_5Cycles); /* 239.5 Cycles as sampling time */

  ADC_GetCalibrationFactor(ADC1); /* ADC Calibration */
  ADC_Cmd(ADC1, ENABLE); /* Enable ADCperipheral */

  while(!ADC_GetFlagStatus(ADC1, ADC_FLAG_ADEN)); /* Wait the ADCEN flag */

  ADC_ChannelConfig(ADC1, ADC_Channel_0 , ADC_SampleTime_13_5Cycles); /* set the sample time */
// end of adc init code ...
}


void usart_init(void)
{
    RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE); /* Enable GPIO clock */

    GPIO_PinAFConfig(GPIOA, GPIO_PinSource9, GPIO_AF_1);    /* Connect PXx to USARTx_Tx */

    GPIO_InitTypeDef GPIO_InitStructure;
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; /* Configure USART Tx as alternate function push-pull */
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
    GPIO_Init(GPIOA, &GPIO_InitStructure);

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; /* Configure USART Rx as simple output function push-pull */
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
    GPIO_Init(GPIOA, &GPIO_InitStructure);


    RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE); /* Enable USART clock */

    USART_InitTypeDef USART_InitStructure;
    USART_InitStructure.USART_BaudRate = 115200; /* USART configuration */
    USART_InitStructure.USART_WordLength = USART_WordLength_8b;
    USART_InitStructure.USART_StopBits = USART_StopBits_1;
    USART_InitStructure.USART_Parity = USART_Parity_No;
    USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
    USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
    USART_Init(USART1, &USART_InitStructure);

    USART1->CR3 |= 8; // set HDSEL -> Single-wire half-duplex communication

    USART_Cmd(USART1, ENABLE); /* Enable USART */

    NVIC_EnableIRQ(USART1_IRQn); //
    NVIC_SetPriority(USART1_IRQn, 0); //
    USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
// end of usart init code ...
}


/*
 1  BOOT0
 2  OSC_IN (PF0)
 3  OSC_OUT (PF1)
 4  NRST
 5  VDD_A
 6  PA0 USART1_CTS ; ADC_IN0,RTC_TAMP2,WKUP1
 7  PA1 USART1_RTS,EVENTOUT ; ADC_IN1
 8  PA2 USART1_TX ; ADC_IN2
 9  PA3 USART1_RX ; ADC_IN3
10  PA4 SPI1_NSS,USART1_CK,TIM14_CH1 ; ADC_IN4
11  PA5 SPI1_SCK ; ADC_IN5
12  PA6 SPI1_MISO,TIM3_CH1,TIM1_BKIN,TIM16_CH1,EVENTOUT ; ADC_IN6
13  PA7 SPI1_MOSI,TIM3_CH2,TIM14_CH1,TIM1_CH1N,TIM17_CH1,EVENTOUT ; ADC_IN7
14  PB1 TIM3_CH4,TIM14_CH1,TIM1_CH3N ; ADC_IN9
15  VSS
16  VDD
17  PA9 USART1_TX,TIM1_CH2,I2C1_SCL
18  PA10 USART1_RX,TIM1_CH3,TIM17_BKIN,I2C1_SDA
19  PA13 IR_OUT,SWDIO
20  PA14 SWCLK



p1:
a4 button0 (led)-jumper-gnd
a3 adc3
a2 adc2
a1 adc1
a0 adc0
vdda
nrst
osc/o
osc/i
boot0


p2:
5v
3v3
a5 button1
a6 (b0t0)
a7 button2
b1 button3
a9 tx
a10 rx
a13 dio
a14 clk


j3:
gnd
tx tx/rx network
rx network -> rs485 Driver Output Enable
3v3

j4:
gnd
clk
dio
3v3

jumpers:
led
b0t0
vdda

*/

/* swd (jlink):
 * bas :
 * vert sous 1ère pin encoche
 * haut (encoche) :
 * jaune  2ème pin encoche
 * orange à droite de jaune
 * rouge dernière pin (sous triangle)
 */

Title: Re: STM32, ghetto style
Post by: jaxbird on January 26, 2015, 06:54:21 pm
Threads like this with naked mcu's (no caps or resistors) really need to be R rated and flagged as NSFW

(https://www.eevblog.com/forum/microcontrollers/stm32-ghetto-style/?action=dlattach;attach=105412;image)

Please think of the kids browsing here

;D

Title: Re: STM32, ghetto style
Post by: Koepi on January 26, 2015, 07:14:45 pm
Agreed, that nice soldering work there is nerd-porn at its best :D
Title: Re: STM32, ghetto style
Post by: dannyf on January 26, 2015, 07:16:54 pm
Quote
the price should be less than 2$

I guess I got cheated, :)

$2 is an excellent price for your board. That's with delivery I assume?
Title: Re: STM32, ghetto style
Post by: trimarco232 on January 26, 2015, 08:21:27 pm
Unfortunately not, the best price incl shipping is 4$08 at aliexpress
I bought mine at taobao as part of a whole sale, in order to minimize handling an shipping fees. The bare price 1$80.
Title: Re: STM32, ghetto style
Post by: Ribster on June 02, 2015, 09:12:56 pm
Hey guys,

In follow up of the ghetto project, i created my own bare board and some files on github.
I used the code from dannyf for the HSI initialization, the rest is from the stdlib examples / self coded.

IDE is eclipse, with gcc as compiler.
Board is made in Altium, just a simple breakout..

Github repo:
https://github.com/Ribster/STM32-Projects/tree/master/stm32dev%20for%20STM32F030%20 (https://github.com/Ribster/STM32-Projects/tree/master/stm32dev%20for%20STM32F030%20)

Schematic of the PCB
https://github.com/Ribster/STM32-Projects/blob/master/stm32dev%20for%20STM32F030%20/ALT0062%20-%20STM32F030%20breakout/ALT0062%20-%20STM32F030%20breakout.pdf (https://github.com/Ribster/STM32-Projects/blob/master/stm32dev%20for%20STM32F030%20/ALT0062%20-%20STM32F030%20breakout/ALT0062%20-%20STM32F030%20breakout.pdf)

For 2 examples, i made a small video.
https://www.youtube.com/watch?v=l=https://github.com/Ribster/STM32-Projects/tree/master/stm32dev%20for%20STM32F030%20]https://github.com/Ribster/STM32-Projects/tree/master/stm32dev%20for%20STM32F030%20 (https://www.youtube.com/watch?v=RYRvpM3fKNs&list=PLRwVP6qPxvbsk3hv16hYOKhaGsn7whQ4j)
Title: Re: STM32, ghetto style
Post by: martinayotte on September 27, 2016, 04:37:16 pm
Okay, you guys are gonna kill me for this..
VDDA wasn't connected on my board...
The good news is, i will shut up now because it's solved :).
Thanks for the support  :-+
Wow ! thanks for this post !
I was search for days why I wasn't able to use HSI with PLL.
It was hanging on RCC_CR_PLLON for me too, I've read that it works for you at lower MUL, then highest I got was MUL4.
Then, I've read about this missing VDDA connection ...
Now it is working perfectly at MUL12 !
Title: Re: STM32, ghetto style
Post by: rob42 on November 04, 2016, 07:56:20 pm
Here is single-sided PCB for STM32F030F4 with more connectors: RS232, LCD, keyboard/encoder, and 7 GPIOs: https://github.com/ncp1402/mcu_stm32f0_ssop20-02

and for TQFP32: https://github.com/ncp1402/mcu_stm32f0_tqfp32-01
Title: Re: STM32, ghetto style
Post by: rainsee on November 11, 2016, 08:42:36 am
 there's the dev board itself -- essentially a small product of its own, with a random combo of stuff you'll use and some you won't.