Cheap STM32 board + Arduino IDE UPD 08/17/2017
- Tutorial
Want to upgrade your Arduino projects? To make them work faster, to make measurements and adjustments more precisely, and add bugs (with new devices they are inevitable). Then this article is for you.
Arduino theme is increasingly captivating the minds of humanity, but sooner or later we encounter the fact that we lack something, such as budget / size /
Good people understand this, and little by little they begin to introduce the STM32 to the Arduino topic , because eight-bit AVR microcontrollers, on which many Arduino boards are based, cannot always cope with the tasks.
A summary of this article in video format:
Okay, less lyrics and closer to the topic. In this article, I will consider a cheap debugging motherboard, which is based on the STM32F103C8T6 microcontroller base :
First, let's compare the main parameters of the STM32 board, and its analogue price - Arduino Nano V3.0:
- The working frequency is 72 MHz, against 16 for the Arduino;
- The amount of flash memory 64 KB, against 32;
- RAM, it is also RAM (where variables are stored), STM32 has as much as 20 Kbytes, and Arduinka has only 2;
- A fast 12-bit ADC, while the Arduino boards, which are based on AVR microcontrollers (this is usually the majority), use a 10-bit one. This means that in the case of STM32, the analogRead (*) function; will return 0..4095 versus 0..1023, which in the first case leads to more accurate measurements;
- 16-bit hardware PWM, versus 8 in Arduino boards, that is, the
analogWrite (*)function;pwmWrite (*); can take the value 0..65535, against the poor 0..255. This will allow even more precise control of our engines, servami and other devices that are driven by PWM; - Hardware work with USB, more than one Arduino board worth less than $ 2 cannot boast;
- Power supply - from 2 to 3.6V (just sharpened for 2 AA batteries), against 2.7 ... 5V for Arduino boards;
- Prices at the time of this writing - 1.9 dollars against 1.8 (aliexpress).
Obviously, the development board based on the STM32 wins on all parameters in Arduino Nano, an exception is perhaps that the cost, but you will agree 10 cents - a good price for a great performance, but about the periphery, which is stuffed STM32, so I generally keep quiet, which only cost DMA or real-time clock integrated into the microcontroller.
All this in total makes this board extremely attractive in everything except one - for a beginner, like me, the STM32 theme seems too time consuming, there are entire websites dedicated to programming these microcontrollers. But if you make friends with the STM32 Arduino IDE, the threshold of entry drops to an extremely low level. Although, as they say, "In each barrel of honey, there is a fly in the ointment," but more on that below.
Let's start preparing the board, to work with the Arduino IDE. The first thing that needs to be done is to upload a special bootloader to the microcontroller, which will allow to flash the board through hardware USB, and directly from the development environment. To do this, move the upper jumper (aka “BOOT0”) to the “1” position:
What are BOOT0 and BOOT1 jumpers for?
Дело в том, что в STM32 с завода прошит, в так называемую системную память(system memory), специальный загрузчик, который позволяет прошивать плату через самый обычный USB to UART переходник, не прибегая к специфическим программаторам типа ST-Link V2.
Next we need an adapter from USB to UART. It is worth remembering that the STM32, this 3.3 V logic , compatibility with 5 volts is not guaranteed, therefore it is recommended to use USB to UART, which has the ability to select modes of operation with 3.3 / 5V logic. I used a cheap CH340G-based adapter:
* as you can see, the manufacturer did not wrap up with the flux remover, of course, it doesn’t affect the work.
I connected the adapter to the USB to UART adapter as follows:
G <-> GND;
5V <-> 5V;
PA10 <-> TXD;
PA9 <-> RXD.
* PA10 / PA9 on the board are simply signed as A10 / A9 - these ports are the first hardware USART, all of them are on board 3, there are also 2 hardware I2C and 2 SPI.
For the sake of convenience, it powered the board from 5 V, for power supply from 3.3 V there is a pin “3.3” on the board. Attention, 5 V can easily disable the microcontroller , so pay due attention to the connection.
We download, install and run Flash Loader Demonstrator (available in the archive for the article):
Select the COM port number of our adapter, in my case it is COM43, then click “Next”:
Since I have a new microcontroller, I have
Click “OK”:
Since my debug board is based on the STM32F103 C8 microcontroller - here is 64 Kbytes of Flash memory, there is also an STM32F103 CB microcontroller, where Flash is twice as large.
Next, click "Next":
Again, "Next", and see the following window:
Select "Download to device" and click on the "...":
We change the file type to * .bin and open the file “generic_boot20_pc13.bin” (also present in the archive) which can be taken from the STM32duino-bootloader project .
Next, click on the button “Next”, after the bootloader firmware, we will see the green light:
Then you need to download, for the Arduino IDE development environment, a special STM32 kernel (also available in the archive for the article).
Proven kernel performance on the Arduino IDE version 1.6.9 .
Next, unzip the contents to My Documents \ Arduino \ hardware:
In my case, the full path looks like this - “C: \ Users \ RSK \ Documents \ Arduino \ hardware”
Of course, the system will not be able to determine the device, so you must also install the drivers on the board. Go to the folder "My Documents \ Arduino \ hardware \ Arduino_STM32 \ drivers \ win" (or "drivers \ win", in the case of an archive to the article), and run the file "install_drivers.bat" as administrator:
After that, the top jumper ( that “BOOT0”), translate to the “0” position and connect the board to the computer via microUSB cable:
It should be defined in the device manager either as “Maple DFU” or “Maple Serial (COM *)”:
It's not entirely clear why after the first connection the board is defined differently, on different computers, but not the essence, proceed to configure the Arduino IDE.
Launch the development environment, then Tools ->
Board -> Boards Manager: Here you need to install the core for the Arduino Due board. Select the latest version and click "Install":
Then Tools -> Board -> "Generic STM32F103C", then Variant: "STM32F103C8 (20k RAM. 64k Flash)", Upload Method: "STM32duino bootloader", Port - number of the COM port of the board , in general, everything is like on the screen:
Everything, the board is ready for firmware and programming in the Arduino IDE development environment. Let's skip some sketch from the examples that are “stitched” into the kernel, go to File -> Sketch folder -> hardware -> Arduino_STM32 -> STM32F1 -> libraries -> A_STM32_Examples -> Digital -> Blink:
Classic “Hello World” in the world of microcontrollers. Change PB1 to PC13, because the LED on the board,
* By the way, it lights up at a low level on the leg of PC13.
Press the “Load” button, after the firmware, the development environment will display something like:
“Done!
Resetting USB, Switch, Win
error: Unable to find the specified file. ".
But the firmware is loaded successfully, although not always the case, sometimes the Arduino IDE issues other messages.
Couldn't find the DFU device
Когда видите, сообщение типа:
«dfu-util — © 2007-2008 by OpenMoko Inc.
Couldn't find the DFU device: [1EAF:0003]
This program is Free Software and has ABSOLUTELY NO WARRANTY»
Это означает, что плату прошить не удалось.
«dfu-util — © 2007-2008 by OpenMoko Inc.
Couldn't find the DFU device: [1EAF:0003]
This program is Free Software and has ABSOLUTELY NO WARRANTY»
Это означает, что плату прошить не удалось.
Searching for DFU device [1EAF: 0003] ...
Когда среда разработки выдаёт:
«Searching for DFU device [1EAF:0003]…
Assuming the board is in perpetual bootloader mode and continuing to attempt dfu programming...»
И больше ничего не происходит, попробуйте в этот момент перезагрузить плату клацнув кнопку ресет. По аналогии это как с Arduino Pro Mini.
«Searching for DFU device [1EAF:0003]…
Assuming the board is in perpetual bootloader mode and continuing to attempt dfu programming...»
И больше ничего не происходит, попробуйте в этот момент перезагрузить плату клацнув кнопку ресет. По аналогии это как с Arduino Pro Mini.
And now about the “spoon of tar”, which I wrote about at the beginning of the article, for some reason it is not always possible to flash the board in the development environment, even more, it is not always determined by the computer. I decided this for myself as follows, before downloading the firmware (before pressing the “Load” button), click “Reset” on the board, and after the firmware, I reboot the board again. In this case, the percentage of the probability that the board will be flashed is equal to 99%. It is not clear why this is the case, but true. I think that sooner or later this joint will be corrected, and everything will automatically restart as needed. And in order to fix it faster, it is necessary that the community of this wonderful STM32 debug card grows, so share this article with friends, especially with programmer friends.
About pinouts:
Clickable
Лучшее что мне удалось найти, это распиновка самого микроконтроллера(открывайте в новой вкладке):
(с) www.stm32duino.com/viewtopic.php?p=11137
К порту нужно обращаться по полному имени, например:
digitalWrite(PB0, LOW);
analogWrite(PA8, 65535);pwmWrite(PA8, 65535);
analogRead(PA0);
LiquidCrystal lcd(PB0, PA7, PA6, PA5, PA4, PA3);
Ещё рекомендую зайти на сайт docs.leaflabs.com/docs.leaflabs.com/index.html там есть много чего интересного по теме программирования в Arduino IDE, правда на английском языке.
Я порылся в файлах ядра, и нашёл один интересный файл:
Documents\Arduino\hardware\Arduino_STM32\STM32F1\variants\generic_stm32f103c\board.cpp
Там прописаны все порты, которые поддерживают:
Так что имейте это ввиду. Хотя этого более чем достаточно от платы, стоимостью в 1.9 доллара.
Ещё заметил, что пины PA12/PA11 подключены к D+/D- USB, их лишний раз лучше вообще не трогать, ибо чуть что, на кону не 2-х долларовый кусок стеклотекстолита с чипом, а материнская плата компьютера.
(с) www.stm32duino.com/viewtopic.php?p=11137
К порту нужно обращаться по полному имени, например:
digitalWrite(PB0, LOW);
analogRead(PA0);
LiquidCrystal lcd(PB0, PA7, PA6, PA5, PA4, PA3);
Ещё рекомендую зайти на сайт docs.leaflabs.com/docs.leaflabs.com/index.html там есть много чего интересного по теме программирования в Arduino IDE, правда на английском языке.
Я порылся в файлах ядра, и нашёл один интересный файл:
Documents\Arduino\hardware\Arduino_STM32\STM32F1\variants\generic_stm32f103c\board.cpp
Там прописаны все порты, которые поддерживают:
- ШИМ, то есть функция
analogWrite();pwmWrite(); — PB0, PA7, PA6, PA3, PA2, PA1, PA0, PB7, PB6, PA10, PA9, PA8, а это далеко не все, которые размечены на распиновке чипа; - АЦП, аля analogRead(); — PB0, PA7, PA6, PA5, PA4, PA3, PA2, PA1, PA0.
Так что имейте это ввиду. Хотя этого более чем достаточно от платы, стоимостью в 1.9 доллара.
Ещё заметил, что пины PA12/PA11 подключены к D+/D- USB, их лишний раз лучше вообще не трогать, ибо чуть что, на кону не 2-х долларовый кусок стеклотекстолита с чипом, а материнская плата компьютера.
Debug card layout:
Clickable
And lastly:
Hi geektimes.ru
//https://github.com/mk90/LiquidCrystalRus//STM32 в массы!#include<LiquidCrystalRus.h>LiquidCrystalRus lcd(PB9, PB8, PB7, PB6, PB5, PB4);
voidsetup(){
lcd.begin(16, 2);
lcd.print("Привет");
lcd.setCursor(0, 1);
lcd.print("geektimes.ru");
}
voidloop(){
lcd.setCursor(14, 1);
lcd.print(millis() / 1000);
}
Links:
Archive to the article ;
Comrade Roger Clark's website for STM32 porting , questions / suggestions / thanks, everything is there;
https://github.com/rogerclarkmelbourne/Arduino_STM32 ;
http://docs.leaflabs.com/docs.leaflabs.com/index.html - this is the project that Roger took as the basis, so there is a lot of useful things, though in English;
Arduino IDE version 1.6.5-r5 can be downloaded here ;
My article, to some extent intersects with the " STM32 vs Arduino " comrade @RaJa ;
Datasheet on STM32F103C8T6 ;
All my publications are on geektimes .
UPD 07.15.2016
Proven kernel performance on the Arduino IDE version 1.6.9:
geektimes.ru/post/277928/#comment_9532576
PS
What else did you forget
Забыл добавить фото платы с обратной стороны:
Тут почти ничего нет, стабилизатор и немного резисторов с конденсаторами.
Так же не рассказал, что дополнительно пропаивал microUSB разъем:
Потому что не особо внушала доверие пайка, точнее, её полное отсутствие.
Тут почти ничего нет, стабилизатор и немного резисторов с конденсаторами.
Так же не рассказал, что дополнительно пропаивал microUSB разъем:
Потому что не особо внушала доверие пайка, точнее, её полное отсутствие.