Error mass erase operation failed please verify flash protection

Error mass erase operation failed please verify flash protection Плата с контроллером подключена по интерфейсу SWD (SWDIO+SWCLK+питание), программатор ST-Link v2. Пытаюсь стереть прошивку при помощи «STM32 ST-LINK Utility» — подключение проходит нормально, содержимое памяти отображается, нажимаю кнопку «Full chip erase» — открывается соотв. окошко, полоска потихоньку (медленнее, чем при успешном стирании до этого) заполняется, […]

Грязь на линиях питания, наводки на провода программатора. Конденсаторы на питании кристалла стоят? Разводка питания и земли нормальная?

Процедура стирания — дает неплохой мусор на шины питания. Прекрасно работающая схема может сильно чудить при стирании.

Попробуй снизить частоту работы ST-Link.

Реклама

Линейка изолированных DC/DC-преобразователей VCB и VCF с диапазоном мощности 3…400 Вт предназначена для использования в телекоммуникационной аппаратуре. Эти новые преобразователи третьего поколения (R3) выпускаются в типоразмерах SIP, 1/4 Brick, 1/8 Brick и 1/16 Brick. Данные DC/DC отвечают требованиям стандарта DOSA, имеют диапазон входного напряжения 2:1 (36…75 В), обладают высокой эффективностью (КПД до 93%) и широким температурным диапазоном -40…85ºС. Изоляция «вход-выход» составляет 1500/2250 В. VCB и VCF выпускаются в двух вариантах по логике управления: N (отрицательной) и P (положительной).

Часовой пояс: UTC + 3 часа

Кто сейчас на форуме

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 13

Источник

STM32F091RC: Flashing fails (#356, but mass erase does not work) #612

  • Programmer/board type: Stlink/v2
  • Operating system: Linux
  • Stlink commandline tool name: st-flash & st-util
  • Target chip (and optional board): STM32F091RC

I am seeing the issue mentioned in : #356

I tried mass erase and flash but that did not work.

Expected/description:
Should be able to flash without issues

The text was updated successfully, but these errors were encountered:

I could reproduce it again today.

Mass erase did not work.

But when i unplugged st-link from power and connected back(basically reset st-link), i was able to flash..

Hi, same problem on L073RZ.
Mass erase did not work. Reset did not work too.
It works some time but not a lot .
Always this errors :
st-flash 1.4.0-1-g5e740a8
2017-07-06T15:51:16 INFO src/common.c: Loading device parameters.
2017-07-06T15:51:16 INFO src/common.c: Device connected is: L0x Category 5 device, id 0x20086447
2017-07-06T15:51:16 INFO src/common.c: SRAM size: 0x5000 bytes (20 KiB), Flash: 0x30000 bytes (192 KiB) in pages of 128 bytes
2017-07-06T15:51:16 INFO src/common.c: Attempting to write 105836 (0x19d6c) bytes to stm32 address: 134217728 (0x8000000)
Flash page at addr: 0x08019d00 erased
2017-07-06T15:51:22 INFO src/common.c: Finished erasing 827 pages of 128 (0x80) bytes
2017-07-06T15:51:22 INFO src/common.c: Starting Half page flash write for STM32L core id
2017-07-06T15:51:22 INFO src/flash_loader.c: Successfully loaded flash loader in sram
2017-07-06T15:51:26 ERROR src/flash_loader.c: flash loader run error
2017-07-06T15:51:26 WARN src/common.c: l1_stlink_flash_loader_run(0x8000000) failed! == -1
2017-07-06T15:51:26 WARN src/common.c:
write_half_pages failed == -1
825/826 pages written
2017-07-06T15:53:05 INFO src/common.c: Starting verification of write complete
2017-07-06T15:53:07 INFO src/common.c: Flash written and verified! jolly good!

Of course it’s not working.

I had this issue, and resolved it by bringing my st-link firmware up-to-date using the windows utility. It now functions in linux perfectly.

Update: After firmware update, I was able to flash my own code, but I was still unable to flash the bootloader using st-flash or gdb. The windows utility reported that the pages involved were write-protected in the option bytes. When told to program the area, it was able to disable the write protection, flash, and then re-enable it, which I suppose is a feature that st-flash lacks.

Источник

Русские Блоги

STM32: Операции стирания, чтения и записи Flash (библиотека HAL)

  • Платформа приложения: STM32F030F4P6
  • ST официальная библиотека: STM32Cube_FW_F0_V1.9.0

Базовые знания

  • В подавляющем большинстве микроконтроллеров и микроконтроллеров (ARM, x86) адресное пространство находится в байтах, то есть адрес является байтом.
  • Одной из характеристик флэш-памяти является то, что она может записывать только 0, а не 1. Таким образом, если исходный адрес содержит данные, это означает, что некоторые биты равны 0, эти биты эквивалентны недействительным. Таким образом, вы должны убедиться, что все они равны 1, прежде чем писать, необходимо только удаление. Кроме того, каждое стирание должно стирать сектор 4K, который определяется характеристиками вспышки.
  • Внутренний генератор должен быть включен до вспышки.

STM32F030F4P6 Введение во флэш-память

Конфигурация оборудования STM32F030F4P6: флэш-память (16 КБ), ОЗУ (4 КБ)
(содержит 4 сектора, 1 сектор содержит 4 страницы, каждая страница имеет пространство 1 Кбайт)
Пользователи могут выполнять Flash program и erase Операция.

Main Flash memory programming
The main Flash memory can be programmed 16 bits at a time.
Flash memory erase
The Flash memory can be erased page by page or completely (Mass Erase).

Flash memory addresses Size(byte) Name Description
0x0800 0000 — 0x0800 03FF 1 Kbyte Page 0 Sector 0
0x0800 0400 — 0x0800 07FF 1 Kbyte Page 1 Sector 0
0x0800 0800 — 0x0800 0BFF 1 Kbyte Page 2 Sector 0
0x0800 0C00 — 0x0800 0FFF 1 Kbyte Page 3 Sector 0
0x0800 1000 — 0x0800 13FF 1 Kbyte Page 4 Sector 1
0x0800 1400 — 0x0800 17FF 1 Kbyte Page 5 Sector 1
0x0800 1800 — 0x0800 1BFF 1 Kbyte Page 6 Sector 1
0x0800 1C00 — 0x0800 1FFF 1 Kbyte Page 7 Sector 1
0x0800 2000 — 0x0800 23FF 1 Kbyte Page 8 Sector 2
0x0800 2400 — 0x0800 27FF 1 Kbyte Page 9 Sector 2
0x0800 2800 — 0x0800 2BFF 1 Kbyte Page 10 Sector 2
0x0800 2C00 — 0x0800 2FFF 1 Kbyte Page 11 Sector 2
0x0800 3000 — 0x0800 33FF 1 Kbyte Page 12 Sector 3
0x0800 3400 — 0x0800 37FF 1 Kbyte Page 13 Sector 3
0x0800 3800 — 0x0800 3BFF 1 Kbyte Page 14 Sector 3
0x0800 3C00 — 0x0800 3FFF 1 Kbyte Page 15 Sector 3

STM32F030F4P6 Флэш-код для чтения и записи (библиотека HAL)

Источник

MCU on Eclipse

Everything on Eclipse, Microcontrollers and Software

Unlocking and Erasing FLASH with Segger J-Link

When using a bootloader (see “Serial Bootloader for the Freedom Board with Processor Expert“), then I usually protect the bootloader FLASH areas, so it does not get accidentally erased by the application ;-). When programming my boards with the P&E Multilink, then the P&E firmware will automatically unlock and erase the chip. That’s not the same if working with the Segger J-Link, as it but requires extra steps.

Protected FLASH Pages with Processor Expert

Protected FLASH Pages with Processor Expert

Failed Programming with protected FLASH

If I try to re-program the protected bootloader with Segger J-Link (both in CodeWarrior and Eclipse/KDS with GDB), then the download silently fails. The effect is that somehow the application on the board does not match what it should be. Looking at the Console view, it shows that erase has failed (but no real error reported) :-(:

J-Link Failed to Erase in CodeWarrior

J-Link Failed to Erase in CodeWarrior

The GNU ARM Eclipse Segger integration with GDB (e.g. Kinetis Design Studio) is not better: no error sign, the only thing is a hidden ERROR in the Console log of the JLinkGDBServerCL:

ERROR Algo135 Flash Protection Violation about failed FLASH Programming

ERROR Algo135 Flash Protection Violation about failed FLASH Programming

What I need is to unprotect the memory and then erase it.

Erasing

The Segger J-Link features a very fast programming. Part of that speed is that the Segger firmware checks each FLASH page if it really needs to be programmed, and only then it erases and reprogrammed that page. So downloading twice the same application actually will not touch the FLASH memory at all. Additionally, it does not do a complete erase of the device: it only programs the pages I’m using in my application. The advantage of that is first speed. And it does not erase the application data I’m using in non-volatile memory (see “Configuration Data: Using the Internal FLASH instead of an external EEPROM“). However, sometimes I really need to clear all my data in FLASH too, and then I need to erase all my FLASH pages on the device.

Segger has product named ‘J-Flash’ which is used to Flash and Erase devices outside of an IDE. There is a free-of-charge ‘Lite’ version available for download from Segger. This utility is not intended to be used for production. With this utility I have a GUI to erase and program my device.

But J-Flash Lite cannot unlock my locked FLASH pages :-(.

If my device is not locked, I can use the CodeWarrior ‘Flash file to target’ (see “Flashing with a Button (and a Magic Wand)“) to erase the device:

Erasing Device with Flash File to Target

Erasing Device with Flash File to Target

Again, this does not work if the device is locked. CodeWarrior has another feature called ‘Target Task’ which can be used to erase/unsecure (if your device is supported), see “Device is secure?“.

So I need to use a different tool to unlock and unprotect my device: the J-Link Commander.

Unlocking and Erasing with J-Link Commander

To unlock the device, Segger has a utility named ‘J-Link Commander’, available from http://www.segger.com/jlink-software.html. The binary is ‘jlink.exe’ on Windows and is a command line utility. To unlock the device use

But it seems that I need to do an unlock, followed by an erase to make it permanent. To erase the device, I can use the same command line utility. But I need to specify the device name first, and then I can erase it (example for the KL25Z):

❗ I need to do the erase operation right after the unlock. a) set device b) unlock and c) erase, otherwise it will fail?

Unlocking and Erasing with J-Link Commander

Unlocking and Erasing with J-Link Commander

Summary

In order to re-program the protected FLASH sectors with Segger J-Link, I need first to unlock and mass erase the device. For this, there is the J-Link Commander utility which has a command line interface to unprotect and erase the device. For erasing only, the J-Flash (and Lite) is a very useful tool, especially to get a ‘clean’ device memory.

To me, the Segger way and tools are very powerful. In this case, things are very flexible, but not that obvious. So I hope this post can help others to get his device unlocked and erased.

Like this:

Related

About Erich Styger

18 thoughts on “ Unlocking and Erasing FLASH with Segger J-Link ”

KDS shoud have an option to unlock flash or at least hint user more precisely what to do in its log.
Thank you for this this exlanation. It saved me a lot of time.

I am trying to use similar procedure as yours to “erase my secure Kinetis KV31 device”, I use J-link utility – unfortunately I can’t erase it due to device is secured.

J-Link>unlock Kinetis
Found SWD-DP with ID 0x2BA01477
Unlocking device…O.K.

J-Link>erase
Erasing device (MKV31F512xxx12)…

****** Error: Failed to erase sectors 8 @ address 0x00004000 (Algo135: Flash pro
tection violation. Flash is write-protected.)
Info: J-Link: Flash download: Total time needed: 1.155s (Prepare: 0.689s, Compar
e: 0.000s, Erase: 0.067s, Program: 0.000s, Verify: 0.000s, Restore: 0.398s)
ERROR: Erase returned with error code -5.
J-Link>

Is there a way to unlock secured device and erase it?
I am OK with deleting my flash I just want to reprogram device again.
Thanks for you advice.

Hi Peter,
are you using the latest Segger J-Link firmware and drivers? I do not have a KV device, so cannot try out things on my side. Otherwise I recommend that you contact Segger (they are usually very responsive).

I have had the same problem with the k22f board and jlink opensda 2.1 firmware. It took me a moment to realize I have exactly the same problem as mentioned here because the error message is a little different:

ERROR: Failed to erase sectors 0 @ address 0x00000000 (Algo135: Illegal command)

The cure is exactly as described here, after doing

Thank you for your great blog,

Hi Eric,
I have a problem with my custom pcb which has the k64 as the mcu. I use the segger jlink to program the mcu via swd. for some unknown reason, jlink sometimes can connect to the mcu and then not. I have no clue why it been behaving this way. I know my problem seems not to be related to your article here. But as you are an expert in this field, I would be thankful for your help
thanks in advance

Hi Hung,
first, I would look at the reset line: is it properly pulled up? Is the capacitor on the reset line not too big? If it is to big, then the debug probe might not be able to pull it down fast enough. The other thing with the K64F (and others): make sure you have disable the EZPort of the device, as otherwise the device wants to load/boot from the EZPort.
I hope this helps,
Erich

HI Erich
I Had the “Device is secured” problem on 2 of 5 MKV31F devices.
Using universal multilink i had no way to unlock it,and the odd thing is that one of the devices was new,so i was not able to flash it for the very first time.The project that i tred to load was working fine with other boards let’s call it “A_project”.
I built an almost empty project,let’s call it “Dummy” and i have found a difference in Hex files:
In A_project the byte ad address 0x40C=0x7E and in “Dummy” 0x40C=0xFE.,at least the SEC bits were Unsecured,i will check why i haveKEYEN Field= Backdoor key access disabled
Furthermore the reset pin toggles continously(it has 10K to VDD,100nF to GND).
I dont ‘have a Segger J-Link,but almost for shure i should have some demo board with a J_Link on board.
Do you think i can do something?
This is a 100 pins IC,and i ‘m am scared that after changed it by hand ,i could face the same problem.
Many thanks once more.
Diego

Hi Diego,
yes, using a J-Link might work for you. The ‘real’ J-Links have stronger pull down circuit I think so would be better. But give it a try. Ultimately, I always have J-Link at hand for these kind of things. The reason why you see the reset pin toggling is that the device is continuously resetting: it starts, then runs into a hard fault, restarts again, etc. You might try as well to pull down (e.g. push button) the reset line while you connect to the target. This would give the debug probe a chance or larger time window to connect to the microcontroller and halt it. You migt try this several times.
I hope this helps, and good luck!

HI Erich,
will this tool work for all controller, lets say I am using sj 63110 and the memory is locked, I am not able to unblock now, how can I do this please help.
PS this is from cypress and for a eval kit

You need to check the UM08001_JLink.pdf from Segger (J-Link User manual) as the unlocking is specific for each device.
As far as I see Kineits, LM3Sxxx and EFM32Gxxx are supported.
Erich

Similar to the “Kinetis Recovery Utility” you mentioned in a previous post, do you know if it is possible to use JLink to connect to a board where the RESET pin has been set to GPIO via the FOPT config byte?

No, there is no utility for this as far as I know. So in your case the reset pin is still active after power-up until it reads the FOPT register. With JTAG you can reset the device using the JTAG command. So if you are using JTAG, you should be able to connect. If you only have SWD, then you need to be able to connect with the debugger during this tiny window. So I would try to debug it while the microcontroller is powered up. You might need 10, 50, 100 or more tries, but I think this is what you can do.
The other way is that you add a button to the reset pin and pull it to GND. Give it a try.

regarding your post I’m having a similar problem with internal KE02 EEPROM.
I’m using KDS (3.2.0) with Segger JLink Plus ( V622d ) on MKE02Z64xxx4 and I get the following silent error on the console:
Downloading 82 bytes @ address 0x10000004 – Verify failed
Downloading 4 bytes @ address 0x10000058 – Verify failed
Downloading 52 bytes @ address 0x1000005C – Verify failed
Downloading 4 bytes @ address 0x10000090 – Verify failed
Downloading 40 bytes @ address 0x10000094 – Verify failed

also in GDB server log file:
03-00000000-00-00001636-0029: Downloading 82 bytes @ address 0x10000004
02-00000000-00-00001681-01FA: T1768 001:637 JLINK_WriteMem(0x10000004, 0x0052 Bytes, …) – Data: 00 46 00 50 00 28 00 28 00 05 00 3C 00 46 A4 01 … — CPU_ReadMem(4 bytes @ 0xE000ED90) — ————————————– — Start of determining dirty areas in flash cache — End of determining dirty areas — Start of preparing flash programming — Calculating RAM usage — RAM usage = 4096 Bytes — Preserving CPU registers — Preparing memory — Determining CPU clock frequency — CPU frequency = 16021 kHz — Preparing target
02-00000000-00-00001794-01AC: — Downloading RAMCode — Checking target RAM & preparing RAMCode — End of preparing flash programming — CPU is running at 16021 kHz. — Start of comparing flash — CRC check was estimated as fastest method — Comparing range 0x0000 – 0xD5FF (107 Sectors, 53 KB), using multi-block CRC calculation — All CRCs match — Comparing range 0xF600 – 0xF7FF (1 Sector, 512 Bytes), using multi-block CRC calculation — All CRCs match
02-00000000-00-00001880-01F0: — Comparing range 0x0000 – 0xD5FF (107 Sectors, 53 KB), using alternative multi-block CRC calculation — All CRCs match — Comparing range 0xF600 – 0xF7FF (1 Sector, 512 Bytes), using alternative multi-block CRC calculation — All CRCs match — End of comparing flash — Start of erasing sectors — End of erasing sectors — Start of flash programming — End of flash programming — Start of verifying flash — End of verifying flash — Start of restoring — Restoring RAMCode — Restore target
02-00000000-00-00001882-012A: — Restore memory — Restoring CPU registers — End of restoring — Bank 0 @ 0x00000000: Skipped. Contents already match — Bank 0 @ 0x00000000: Skipped. Contents already match — CPU_WriteMem(16 bytes @ 0x1FFFFC00) — CPU_WriteMem(82 bytes @ 0x10000004) returns 0xFFFFFFFF (0246ms, 1002ms total)
02-00000000-00-00001883-00C2: T1768 001:883 JLINK_ReadMem (0x10000004, 0x0052 Bytes, …) — CPU_ReadMem(82 bytes @ 0x10000004) – Data: AA AA AA AA AA AA AA AA AA AA AA AA AA AA AA AA … returns 0x01 (0001ms, 1003ms total)
03-00000000-00-00001884-0010: – Verify failed

Any idea or suggetion to solve the problem?

Thank you very much

Hi Mat,
not sure, as I’m not using that device. But it seems to me that the Segger J-Link has a problem to access/read the internal EEPROM (that’s located at 0x100000000, right?).
Is this related to unlocking the device or just about using the EEPROM? In any case, I think the best would be if you contact the Segger support (they are usually very responsive) about this.
I hope this helps,
Erich

I thought it could be a KDS unlocking problem or advanced settings to be set, but probably you are right.
I will take your advice.

Thank you very much and congratulations for mcuoneclipse 😉

I would like to ask you for advice on your JLink tools. I am
trying to do FLASH erase on my secure Kinetis MKV31F512xxx12 device.

I would like to use J-link for this. Unfortunately I can’t
erase it due to device is secured. I do the following with JLink commander:

You did not provide your JLink commander command, but if you have secured your device with mass erase disabled, there is no way you will be able to recover it. You would have to unsolder your MKV32 and replace it with a new one.

What do you think? Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Источник

Adblock
detector

Форум РадиоКот • Просмотр темы — STM32 новичку в ARM что к чему

Сообщения без ответов | Активные темы

ПРЯМО СЕЙЧАС:

Автор Сообщение

Не в сети

Заголовок сообщения: Re: STM32 новичку в ARM что к чему

СообщениеДобавлено: Пн дек 09, 2019 20:56:54 

Первый раз сказал Мяу!

Зарегистрирован: Чт апр 30, 2015 15:36:18
Сообщений: 22
Откуда: ЯНАО

Рейтинг сообщения: 0

Здравствуйте! Помогите пожалуйста, только-только сел за STM32 с AVR… Спаял платку для STM32F100RBT6, вывел SWD интерфейс. Программатор: STLINK/V2. Для пробы решил через STM32CubeIDE настроить ножку через их графический конфигуратор, сгенерировал код и залил в камень. Вроде всё было хорошо и прошивка залилась. Но потом с какого-то момента (не уловил с какого, настраивал только одну ножку, т.е. никуда абсолютно больше не лез) при прошивке стало показывать ошибку: DEV_TARGET_UNDER_RESET. Данная ошибка говорит о том, что кнопка Reset на плате нажата. Хотя проверял: кондер не закорочен, емкость есть, кнопка исправна, нигде ничего не коротит. В общем попробовал на крайний случай отрезать ножку от кнопки к МК. Не помогло. Всё то же DEV_TARGET_UNDER_RESET.
Попробовал STM32CubeProgrammer. Там есть выбор режимов при подключении: Normal, Hot Plug, Under Reset. Также есть Reset Mode — здесь я перепробовал все варианты, ничего не помогает. Если поставить режим (Mode) Hot Plug, то проиходит соединение с МК, виден его сериный номер, размер памяти и т.п. Но если попытаться залить прошивку (заливаю .elf файл, сгенерированный STM32CubeIDE) то вылазит ошибка:

Если попытаться стереть память, то во всех случаях получаем ошибки, содержащие: Error: Mass erase operation failed.Please verify flash protection.
Перехожу в Option Bytes, считываю значения: RDP не выставлен, т.е. Unchecked: Flash Memory is non read-protected.
Если попытаться выставить флажки на WRP0…WRP31 и применить, то это ничем не заканчивается, программатор начинает бесконечно прошивать МК.

Блин… как теперь удалить этот позор?) Попросил кота пошкрябать дорожку к RESET от кнопки как следует и всё прошло) Только вот не ясно теперь.. Неужели это кондёр пробило?

Последний раз редактировалось khamai Пн дек 09, 2019 21:40:32, всего редактировалось 1 раз.

Вернуться наверх
 

ПрофильПрофиль

 

Реклама

VladislavS

Не в сети

Заголовок сообщения: Re: STM32 новичку в ARM что к чему

СообщениеДобавлено: Пн дек 09, 2019 21:39:37 

Поставщик валерьянки для Кота
Аватар пользователя

Карма: 13

Рейтинг сообщений: 362

Зарегистрирован: Вт май 01, 2018 19:44:47
Сообщений: 2300

Рейтинг сообщения: 0

Куб по умолчанию отключает SWD интерфейс. Тебе надо либо подключить ресет к программатору, либо нажать его рукой при установке соединения, либо переключить ногу boot0 чтобы залитая прошивка не стартовала.

Программисты куба могут очередную звезду на борту рисовать :)

Вернуться наверх
Реклама

khamai

Не в сети

Заголовок сообщения: Re: STM32 новичку в ARM что к чему

СообщениеДобавлено: Пн дек 09, 2019 21:45:09 

Зарегистрирован: Чт апр 30, 2015 15:36:18
Сообщений: 22
Откуда: ЯНАО

Рейтинг сообщения: 0

Куб по умолчанию отключает SWD интерфейс. Тебе надо либо подключить ресет к программатору, либо нажать его рукой при установке соединения, либо переключить ногу boot0 чтобы залитая прошивка не стартовала.

Программисты куба могут очередную звезду на борту рисовать :)

Да я BOOT коротил на 3.3 — не помогало. В том то и дело, что куб SWD не отключил. Дело было именно в кнопке…

Последний раз редактировалось aen Вт янв 21, 2020 21:17:48, всего редактировалось 1 раз.
Нарушение Правил форума п. 2.7
Вернуться наверх

Сериг

Не в сети

Заголовок сообщения: Re: STM32 новичку в ARM что к чему

СообщениеДобавлено: Сб дек 14, 2019 20:45:29 

Это не хвост, это антенна
Аватар пользователя

Карма: 11

Рейтинг сообщений: 1

Зарегистрирован: Пт фев 19, 2010 19:39:28
Сообщений: 1451
Откуда: Москва

Рейтинг сообщения: 0

Всех приветствую!
Хочу повторить устройство с сайта http://avr-start.ru/?p=3471#more-3471
Компилятор пока не освоил ни грамма.
Если есть у кого возможность, откомпилируйте пожалуйста проект, чтобы просто кекс загрузить в stmку.
Благодарю!

Вернуться наверх
Реклама

Выгодные LED-драйверы для решения любых задач

КОМПЭЛ представляет со склада и под заказ широкий выбор LED-драйверов производства MEAN WELL, MOSO, Snappy, Inventronics, EagleRise. Линейки LED-драйверов этих компаний, выполненные по технологии Tunable White и имеющие возможность непосредственного встраивания в систему умного дома (димминг по шине KNX), перекрывают практически полный спектр применений: от простых световых указателей и декоративной подсветки до диммируемых по различным протоколам светильников внутреннего и наружного освещения.

Подобрать LED-драйвер>>

Oxford

Не в сети

Заголовок сообщения: Re: STM32 новичку в ARM что к чему

СообщениеДобавлено: Сб дек 14, 2019 22:48:23 

Опытный кот
Аватар пользователя

Карма: 4

Рейтинг сообщений: 10

Зарегистрирован: Вт окт 23, 2012 13:17:25
Сообщений: 822
Откуда: Киселевск

Рейтинг сообщения: 0

Сериг лови

Вложение:



2.zip [5.59 KiB]

Скачиваний: 182


_________________
Инженер R@D

Telegram чат: https://t.me/radiowolf или в поиске приложения @radiowolf. Личка:@cncoxford

Вернуться наверх
Реклама

Реклама

LIMF – источники питания High-End от MORNSUN со стандартным функционалом на DIN-рейку

На склад Компэл поступили ИП MORNSUN (крепление на DIN-рейку) с выходной мощностью 240 и 480 Вт. Данные источники питания обладают 150% перегрузочной способностью, активной схемой коррекции коэффициента мощности (ККМ; PFC), наличием сухого контакта реле для контроля работоспособности (DC OK) и возможностью подстройки выходного напряжения. Источники питания выполнены в металлическом корпусе, ПП с компонентами покрыта лаком с двух сторон, что делает ее устойчивой к соляному туману и пыли. Изделия соответствуют требованиям ANSI/ISA 71.04-2013 G3 на устойчивость к коррозии, а также нормам ATEX для взрывоопасных зон.

Подробнее>>

afz

Не в сети

Заголовок сообщения: Re: STM32 новичку в ARM что к чему

СообщениеДобавлено: Вс дек 15, 2019 08:40:19 

Опытный кот
Аватар пользователя

Карма: 12

Рейтинг сообщений: 159

Зарегистрирован: Сб дек 22, 2012 08:17:42
Сообщений: 744
Откуда: Караганда, Казахстан

Рейтинг сообщения: 0

А разве выложенное там test_nokiatest_nokiaDebugbin>test_nokia.hex не годится?


_________________
Кто мешает тебе выдумать порох непромокаемый? (К. Прутков, мысль № 133)

Вернуться наверх

Сериг

Не в сети

Заголовок сообщения: Re: STM32 новичку в ARM что к чему

СообщениеДобавлено: Пн дек 16, 2019 18:21:46 

Это не хвост, это антенна
Аватар пользователя

Карма: 11

Рейтинг сообщений: 1

Зарегистрирован: Пт фев 19, 2010 19:39:28
Сообщений: 1451
Откуда: Москва

Рейтинг сообщения: 0

А разве выложенное там test_nokiatest_nokiaDebugbin>test_nokia.hex не годится?

Благодарю!

Вернуться наверх

WiseLord

Не в сети

Заголовок сообщения: Re: STM32 новичку в ARM что к чему

СообщениеДобавлено: Пн дек 16, 2019 23:49:41 

Друг Кота
Аватар пользователя

Карма: 85

Рейтинг сообщений: 1007

Зарегистрирован: Чт апр 11, 2013 11:19:59
Сообщений: 4825
Откуда: Минск

Рейтинг сообщения: 0

Вопрос — как настроить (на STM32F1) складывание результатов АЦП в массив байтов?

Сейчас настроено следующим образом:
— выравнивание результата АЦП — вправо (получается в регистре АЦП DR число по маске 00000FFF).
— буфер АЦП — массив int16_t значений на N ячеек. Получается, каждый запуск АЦП складывает числа в массив по маскам: 0FFF, 0FFF, 0FFF…., по достижении конца массива — начинает сначала.
— DMA настроен в режиме HalfWord периферия, HalfWord память, адрес периферии ADC1->DR, адрес памяти — начало массива.

Всё прекрасно работает при таких настройках.

Но хочется попробовать сэкономить память на буфере DMA и обойтись массивом uint8_t значений и, соответственно, 8-битной точностью АЦП (т.е. нужны только часть битов результата 00000FFF)

То есть, нужно, чтобы старшие использовались только старшие 8 бит результата измерения и складывались в очередную 8-битную ячейку массива.

Первое, что приходит на ум — выравнивание влево, т.е., чтобы результат в DR был по маске 0000FFF0.

Вопрос, как заставить DMA класть в 8-бит ячейку памяти именно эту часть результата, а не младший байт? Потому что в режиме 16->8 DMA вроде как именно младший байт берёт

Вернуться наверх

Reflector

Не в сети

Заголовок сообщения: Re: STM32 новичку в ARM что к чему

СообщениеДобавлено: Вт дек 17, 2019 00:10:51 

Поставщик валерьянки для Кота

Карма: 20

Рейтинг сообщений: 251

Зарегистрирован: Вс июн 19, 2016 09:32:03
Сообщений: 1950

Рейтинг сообщения: 0

Вопрос, как заставить DMA класть в 8-бит ячейку памяти именно эту часть результата, а не младший байт?

Никак. На всех остальных сериях, кроме F1, можно выбрать 8-ми битный режим для самого ADC.

Вернуться наверх

Sergi

Не в сети

Заголовок сообщения: Re: STM32 новичку в ARM что к чему

СообщениеДобавлено: Вт дек 17, 2019 06:30:02 

Карма: 5

Рейтинг сообщений: 44

Зарегистрирован: Ср янв 04, 2012 11:57:40
Сообщений: 386
Откуда: Алчевск

Рейтинг сообщения: 0

А нельзя ли применить адресацию к старшему байту ADC->DR как к GPIOx->ODR? Я вот так пишу в старший байт GPIOB->ODR данные для 8ми битного дисплея #define LCD (*(__IO uint8_t *)((uint32_t)&(GPIOB->ODR) + 1))

Вернуться наверх

VladislavS

Не в сети

Заголовок сообщения: Re: STM32 новичку в ARM что к чему

СообщениеДобавлено: Вт дек 17, 2019 07:23:17 

Поставщик валерьянки для Кота
Аватар пользователя

Карма: 13

Рейтинг сообщений: 362

Зарегистрирован: Вт май 01, 2018 19:44:47
Сообщений: 2300

Рейтинг сообщения: 0

Я вот так пишу в старший байт GPIOB->ODR данные для 8ми битного дисплея

На F1 такое не прокатит.

Вернуться наверх

Sergi

Не в сети

Заголовок сообщения: Re: STM32 новичку в ARM что к чему

СообщениеДобавлено: Вт дек 17, 2019 07:27:58 

Карма: 5

Рейтинг сообщений: 44

Зарегистрирован: Ср янв 04, 2012 11:57:40
Сообщений: 386
Откуда: Алчевск

Рейтинг сообщения: 0

Как бы на пилюле 103c8 дисплей nokia3230 работает.

Вернуться наверх

VladislavS

Не в сети

Заголовок сообщения: Re: STM32 новичку в ARM что к чему

СообщениеДобавлено: Вт дек 17, 2019 07:35:35 

Поставщик валерьянки для Кота
Аватар пользователя

Карма: 13

Рейтинг сообщений: 362

Зарегистрирован: Вт май 01, 2018 19:44:47
Сообщений: 2300

Рейтинг сообщения: 0

Вложения:


gpio.png [125.14 KiB]

Скачиваний: 263

Вернуться наверх

Sergi

Не в сети

Заголовок сообщения: Re: STM32 новичку в ARM что к чему

СообщениеДобавлено: Вт дек 17, 2019 07:40:41 

Карма: 5

Рейтинг сообщений: 44

Зарегистрирован: Ср янв 04, 2012 11:57:40
Сообщений: 386
Откуда: Алчевск

Рейтинг сообщения: 0

Ну хорошо, а с ADC->DR так читать можно?

Вернуться наверх

VladislavS

Не в сети

Заголовок сообщения: Re: STM32 новичку в ARM что к чему

СообщениеДобавлено: Вт дек 17, 2019 07:49:26 

Поставщик валерьянки для Кота
Аватар пользователя

Карма: 13

Рейтинг сообщений: 362

Зарегистрирован: Вт май 01, 2018 19:44:47
Сообщений: 2300

Рейтинг сообщения: 0

Читаю RM вслух, дорого! Раздел 11.12.

Вернуться наверх

Sergi

Не в сети

Заголовок сообщения: Re: STM32 новичку в ARM что к чему

СообщениеДобавлено: Вт дек 17, 2019 08:00:13 

Карма: 5

Рейтинг сообщений: 44

Зарегистрирован: Ср янв 04, 2012 11:57:40
Сообщений: 386
Откуда: Алчевск

Рейтинг сообщения: 0

Я читал RM. Наверное с доступом это не документированные особенности, так как дисплей работает. На старшем байте шина данных,на младшем WR,энкодер,кнопки и EPROM.

Вернуться наверх

VladislavS

Не в сети

Заголовок сообщения: Re: STM32 новичку в ARM что к чему

СообщениеДобавлено: Вт дек 17, 2019 08:09:41 

Поставщик валерьянки для Кота
Аватар пользователя

Карма: 13

Рейтинг сообщений: 362

Зарегистрирован: Вт май 01, 2018 19:44:47
Сообщений: 2300

Рейтинг сообщения: 0

Как писал М.Н.Задорнов, у русских есть три степени запрета:
1. Запрещено. Это не для меня.
2. Строго запрещено. Надо посмотреть, что же там такое.
3. Категорически запрещено. Ну это уж точно нельзя.

Вернуться наверх

Sergi

Не в сети

Заголовок сообщения: Re: STM32 новичку в ARM что к чему

СообщениеДобавлено: Вт дек 17, 2019 08:15:29 

Карма: 5

Рейтинг сообщений: 44

Зарегистрирован: Ср янв 04, 2012 11:57:40
Сообщений: 386
Откуда: Алчевск

Рейтинг сообщения: 0

Повторю,а с ADC->DR так читать можно?

Вернуться наверх

VladislavS

Не в сети

Заголовок сообщения: Re: STM32 новичку в ARM что к чему

СообщениеДобавлено: Вт дек 17, 2019 08:19:34 

Поставщик валерьянки для Кота
Аватар пользователя

Карма: 13

Рейтинг сообщений: 362

Зарегистрирован: Вт май 01, 2018 19:44:47
Сообщений: 2300

Рейтинг сообщения: 0

Вернуться наверх

Eddy_Em

Не в сети

Заголовок сообщения: Re: STM32 новичку в ARM что к чему

СообщениеДобавлено: Вт дек 17, 2019 08:36:03 

Собутыльник Кота
Аватар пользователя

Карма: -12

Рейтинг сообщений: -18

Зарегистрирован: Пт июл 12, 2019 22:52:01
Сообщений: 2525

Рейтинг сообщения: 0

Sergi, кто вам мешает попробовать? Если в хардфолт не уйдет, то «и так сойдет»…
Мне все-таки непонятно, зачем так извращаться? Настраиваем к ADC нужные каналы DMA, да берем себе данные. У меня на нескольких железяках так опрос работает: в буфер uint16_t с размером 9*[количество каналов] DMA автоматом забивает данные с АЦП. Мне по мере необходимости остается лишь выдрать нужные 9 чисел и сделать быструю медианную фильтрацию. Вуаля!


_________________
Linux rules! Windows must die. Здравомыслящий человек добровольно будет пользоваться мастдаем лишь в двух случаях: под дулом автомата или под влиянием анального зонда.
Я на гитхабе, в ЖЖ

Вернуться наверх

Кто сейчас на форуме

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 5

Вы не можете начинать темы
Вы не можете отвечать на сообщения
Вы не можете редактировать свои сообщения
Вы не можете удалять свои сообщения
Вы не можете добавлять вложения

cron

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Closed

olikraus opened this issue

Jan 30, 2022

· 47 comments


· Fixed by #1653

Assignees

@ABOSTM

Comments

@olikraus

Please, before reporting any issue

  • Make sure you are using the latest Arduino_Core_STM32 version.
    https://github.com/stm32duino/Arduino_Core_STM32/releases/latest
    Oliver: I have installed Arduino Core STM32 last week (2.2.0)
  • Make sure the issue is not already reported/fixed on GitHub or discussed on the stm32duino forum
    Oliver: I have looked for similar problems for STM32G031 but the total number of entries for the STM32G031 is very much limited and do not fit to my case
  • Submit a GitHub issue only for reporting a problem related to the Arduino_Core_STM32.
    Oliver: Difficult to say, but I assume it is a problem within Arduino_Core_STM32
  • Avoid to submit a GitHub issue for project troubleshooting.
    Oliver: I have partly modified Arduino_Core_STM32 as a workaround (see below) and my project is just the Arduino «blink» example.

Any questions/feedback/suggestions should be discussed on the stm32duino forum:

  • questions on the STM32 Core
  • bugs/enhancements on the STM core: Bugs and enhancements

⚠ When reporting any issue, please try to provide all relevant information to help on its resolution.

Describe the bug

  1. After successful upload, the code (Arduino Blink) is not executed by STM32CubeProgrammer (Running the code after upload does not work)
  2. After hardware reset, the code (Arduino) is not executed

To Reproduce

Steps to reproduce the behavior:

  1. Open the Arduino Blink example
  2. Upload the Arduino Blink example
  3. Check whether the LED blinks
  4. Reconfigure target to execute the newly flashed code
  5. Execute a hardware reset on the target
  6. Check whether the LED blinks

Note: I will provide more information with partial findings below in this issue

Expected behavior
The code should be executed from STM32CubeProgrammer and after hardware reset

Screenshots
Here is the protocol of the successful upload (I can provide more screenshots on request)

sh /home/kraus/.arduino15/packages/STMicroelectronics/tools/STM32Tools/2.1.1/stm32CubeProg.sh 1 /tmp/arduino_build_310859/Blink_stm32g0.ino.bin ttyUSB0 -s 
      -------------------------------------------------------------------
                        STM32CubeProgrammer v2.9.0                  
      -------------------------------------------------------------------

Serial Port ttyUSB0 is successfully opened.
Port configuration: parity = even, baudrate = 115200, data-bit = 8,
                     stop-bit = 1,0, flow-control = off
Activating device: OK
Board       : --
Chip ID: 0x466 
BootLoader protocol version: 3.1
Device name : STM32G03x/STM32G04x
Flash size  : 64 KBytes (default)
Device type : MCU
Revision ID : --  
Device CPU  : Cortex-M0+

Memory Programming ...
Opening and parsing file: Blink_stm32g0.ino.bin
  File          : Blink_stm32g0.ino.bin
  Size          : 10332 Bytes
  Address       : 0x08000000 

Erasing memory corresponding to segment 0:
Erasing internal memory sectors [0 5]
Download in Progress:

File download complete
Time elapsed during download operation: 00:00:01.626

RUNNING Program ... 
  Address:      : 0x8000000
Start operation achieved successfully

Desktop (please complete the following information):

  • OS: Ubuntu Linnux
  • Arduino IDE version: 1.8.19
  • STM32 core version: 2.2.0
  • Tools menu settings if not the default: [e.g. Newlib Standard, No Serial]
    • Board: Generic STM32G0 series»
    • Board part number: Generic G031J6MX
    • USART support: Enabled
    • C Runtime Library: Newlib Nano (default)
    • Upload method: STM32CubeProgrammer (serial)
    • Port: /dev/ttyUSB0

Board (please complete the following information):

  • Name: Generic STM32G031J6
  • STM32G031J6 with BOOT0 pin enabled (https://github.com/olikraus/stm32g031/tree/main/enable_boot0) and reset pin disabled (https://github.com/olikraus/stm32g031/tree/main/disable_nrst)
  • USB USART converter connected to PA11/PA10 (pins 5&6)
  • LED connected to PA13

Additional context
LED at PA13 (pin 7 of the SO8N )
I assume pin 7 of the SO8N can be accessed by Arduino pin number 6 (

)
So my initial code looks like this (didn’t execute):

#define MYPIN 6

void setup() {
  pinMode(MYPIN, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
  digitalWrite(MYPIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(MYPIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

Bypassing pinMode and digitalWrite

To debug this, I have bypassed pinMode and digitalWrite:

// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
    //pinMode(MYPIN, OUTPUT);
  GPIOA->MODER &= ~GPIO_MODER_MODE13;  /* clear mode for PA13 */
  GPIOA->MODER |= GPIO_MODER_MODE13_0;  /* Output mode for PA13 */
  GPIOA->OTYPER &= ~GPIO_OTYPER_OT13; /* no Push/Pull for PA13 */
  GPIOA->OSPEEDR &= ~GPIO_OSPEEDR_OSPEED13; /* low speed for PA13 */
  GPIOA->PUPDR &= ~GPIO_PUPDR_PUPD13; /* no pullup/pulldown for PA13 */
  //GPIOA->BSRR = GPIO_BSRR_BR13;   /* atomic clr PA13 */
  GPIOA->BSRR = GPIO_BSRR_BS13;    /* atomic set PA13 */
}

// the loop function runs over and over again forever
void loop() {
  //digitalWrite(MYPIN, HIGH);   // turn the LED on (HIGH is the voltage level)
    GPIOA->BSRR = GPIO_BSRR_BS13;    /* atomic set PA13 */
  delay(1000);                       // wait for a second
  //digitalWrite(MYPIN, LOW);    // turn the LED off by making the voltage LOW
    GPIOA->BSRR = GPIO_BSRR_BR13;    /* atomic clr PA13 */
  delay(1000);                       // wait for a second
}

This code is also not executed, however if -DUSER_VECT_TAB_ADDRESS is used as compiler arguments, then the code gets executed successfully.

I have added this dlag to

compiler.extra_flags=-mcpu={build.mcu} {build.flags.fp} -DUSE_FULL_LL_DRIVER -mthumb «@{build.opt.path}»

like this:

compiler.extra_flags=-mcpu={build.mcu} {build.flags.fp} -DUSE_FULL_LL_DRIVER -mthumb "@{build.opt.path}" -DUSER_VECT_TAB_ADDRESS

This will at least start the above code (blink works), however:

  • any call to pinMode() will again crash the code
  • Startup of the code via hardware reset still doesn’t work (this means: STM32CubeProgrammer can start the code, but HW reset still doesn’t work).

To me it looks like that SCB->VTOR is not setup correctly during startup for the STM32G031.
But there is another bug, because pinMode() still does not work and crashes the code.

Summary

  • Everything works if only delay() is used and SCB->VTOR is assigned correctly
  • A call to pinMode() will halt/crash the code

@ABOSTM

Hi @olikraus,
Thanks for your detailed description.
I tried to reproduce your issue, but I have several concerns:

  • I did not succeed to flash STM32G031J6 with USART(Pin5/6) of my STM32G0316-DISCO.
    According to AN2606, USART1 bootloader is available on PA9/PA10.
    but on SO8N, PA9/PA10 are not available, but rather PA11/PA12 (Pin5/Pin6).
    eventually, stm32g0 has the capability to remap PA11 so that it operates like PA9 (and similarly remap PA12 to operate like PA10).
    I am not sure that bootloader is able to manage this remap (enquiry ongoing).
    So my hypothesis, is that I have an old bootloader which was not able to manage remap, and you have a recent one, which manage the remap. To be confirmed.

  • I made some tests with my Nucleo-G031k8. It is the same, i cannot flash over USART with remap pin PA11/PA12.

  • But on this Nucleo-G031k8, PA9/PA10 are available. So I continue testing with PA9/PA10.
    As I understand, you initially clear option byte nBoot_SEL with you own program so that Boot0 pin is effective (instead of nBOOT0 option byte) and similarly you also disabled NRST pin by setting NRST_MODE= b10 in Option Bytes.
    In your sequence to reproduce this issue, you said:
    4. Reconfigure target to execute the newly flashed code
    Do you mean switch Boot0 pin from logical 0 to 1 ?
    5. Execute a hardware reset on the target
    As you deactivated NRST pin, you could not just act on this pin, so did you power OFF/ON instead ?
    On my side, BOOT0 pin is hardly accessible, so instead I used option Byte nBOOT0.
    So I configured it to run bootloader (nBOOT0=0). I upload the blinky Arduino sketch through usart, and after that, it appear that we are still in bootloader (which seems normal as nBOOT0 is still 0 ), this is confirmed by the fact I can connect with CubeProgrammer in Uart mode, thus I am able to change option byte nBoot0=1 and as soon as I apply it, Arduino code executes.
    So it look to me like there is no issue on my side.

According to your description, it looks like system is still in bootloader mode, which explains that arduino code doesn’t executes. and when enabling USER_VECT_TAB_ADDRESS, the VTOR register is updated, which could lead to execution of code from flash.

  • Concerning pinMode , I have no issue, all my tests above are made with pinMode and digitalWrite (just take arduino example as is). Maybe on your side, it is a side effect of being in Bootloader mode. So let’s fix bootloader issue first.

@ABOSTM

I finally succeed to flash my STM32G0316-DISCO, so I continue my investigations.
I now have access to BOOT0 pin so like you I disabled nBOOT_SEL, and I used BOOT0 pin.
And here is my finding:

  1. Like you I disabled NRST pin: NRST_MODE=b10 (=2)
  • I set BOOT0 = HIGH
  • I upload Arduino blinky through Uart.
    At the end led doesn’t blink as I am still in bootloader
  • I switch BOOT0 = LOW
    led doesn’t blink as I am still in bootloader (normal, a Reset is required)
  • Due to NRST disabled, I power OFF/ON
    —> Led is blinking.
  1. Contrary to you I enable NRST pin: NRST_MODE=b11 (=3)
  • I set BOOT0 = HIGH
  • I upload Arduino blinky through Uart.
    At the end led doesn’t blink as I am still in bootloader
  • I switch BOOT0 = LOW
    led doesn’t blink as I am still in bootloader (normal, a Reset is required)
  • I press the blue button on my Disco which toggles NRST
    —> Led is blinking.

So all seems to work properly

@olikraus



Copy link


Contributor

Author

UPDATE: This is the reply to your first response. Will read your second post soon.

Thanks for testing and your long answer.

You are correct, the option byte has to be modified as mentioned in my inital post. To make the USART upload available, the correct boot0 setup must be available.
As mentioned, I have cleared the boot selection bit:
https://github.com/olikraus/stm32g031/blob/e017b221bc534f08e080d7bd3ded5a41824e8bab/enable_boot0/enable_boot0.c#L78
As a consequence, I can use the BOOT0 pin to define whether to jump into bootloader or not.

As you deactivated NRST pin, you could not just act on this pin, so did you power OFF/ON instead ?

yes correct. I think the problem described here is not related to NRST, but I just wanted to describe my complete setup.
So as a conclusion: If I power on the STM32G0, it either executes flash or starts the bootloader depending on the bootloader.

So, this is the normal (expected) Arduino Upload process:

  1. Code is compiled
  2. Code is uploaded to flash memory of the target device
  3. Code is executed

In my case I want to use «USART», so the precondition in my case is: The device must be in bootloader code and wait for USART upload commands.

All in all steps 1 and 2 work without problem. In fact STM32CubeProgrammer nicely uploads via USART.

My expectation is, that Arduino blink.c will get started after upload and the LED should start to blink.
However: This is not the case, the LED doesn’t blink.

So what are possible failures could be here?

  1. I have used the wrong pin number in blink.c
  2. The code is uploaded to the wrong memory areay (RAM vs Flash???)
  3. The code is not correctly started by STM32CubeProgrammer
  4. Arduino framework has a bug (startup, delay, pinMode, digitalWrite)

At this point I think that there is an issue with stm32duino.

I started to some further investigation:

  1. Arduino Pin Number for PA13? According to the source code, it could be 6, but I am not sure
  2. I do not know whether STM32CubeProgrammer writes to RAM or Flash, but I assume it is flash only
  3. Correct Startup.

Here I figured out, that avoiding pinMode and digitalWrite AND using -DUSER_VECT_TAB_ADDRESS will start the code on the target device.

So, as a conclusion:
I can compile and upload blink.c. I think I have used the correct pin number, but the blink does not work.

I am really happy you replied to this issue. It would be amazing if I could use stm32duino. Please let me what I can do to support the debugging here.

@olikraus



Copy link


Contributor

Author

I finally succeed to flash my STM32G0316-DISCO, so I continue my investigations.

Nice.

I press the blue button on my Disco which toggles NRST

This means, I always have to execute a manual reset, correct?

The question is, why does cubeprogrammer issue this message? My assumption is, that cubeprogrammer directly starts the just downloaded code without reset (which is very much possible).

RUNNING Program ... 
  Address:      : 0x8000000
Start operation achieved successfully

Moreover, even after power on reset, my code is not executed.

Can you confirm that PA13 is used by pinMode(6, …)?

@fpistm

@olikraus



Copy link


Contributor

Author

It had been «Manually Wired».
Let me rebuild the setup from scratch. I will also provide schematics. Again: Thank you both for the support. I will come back with more information.

@olikraus



Copy link


Contributor

Author

I have created a new board with a virgin device:
IMG_20220203_191130166

Soldered on a breakout board:
IMG_20220203_191740427

Final board with schematic:
IMG_20220203_201644104

I have added a normal reset button here.

I can confirm, that this works as described by @ABOSTM (second post):
After upload the automatic start does NOT work. Instead I have switch to normal mode and reset the device.

However, I observe, that the device still freezes if I change something in the code (for example changing the delay time).
In fact it looks like, that the code upload doesn’t work any more if the size of the binary changes.

So, at the moment, I have still two issues:

  1. There is no automatic start of the uploaded code (Workaround: Assign GND to BOOT0 Pin and do a manual reset)
  2. Sometimes does not react any more. (Workaround: Full flash erase required)

@olikraus



Copy link


Contributor

Author

Ok, here is my problem:
I upload this code:

#define MYPIN 6
// the setup function runs once when you press reset or power the board
void setup() {
  pinMode(MYPIN, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
  digitalWrite(MYPIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(300);      
  digitalWrite(MYPIN, LOW);    // turn the LED off by making the voltage LOW
  delay(300);      
}

All works fine, the code size is 13416 bytes
If I change the code like this, then it doesn’t work any more:

#define MYPIN 6
// the setup function runs once when you press reset or power the board
void setup() {
  pinMode(MYPIN, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
  digitalWrite(MYPIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(200);
  digitalWrite(MYPIN, LOW);    // turn the LED off by making the voltage LOW
  delay(200);
}

Code size is now 13412 bytes.

@olikraus



Copy link


Contributor

Author

After some more testing, my result is this:
As soon as the size if the binary code changes, flashing will fail (or at least there is a good chance that flashing will fail).
This can be solved, if the flash memory is fully erased (mass erase). Unfortunately this stm32duino does NOT erase the flash memory.
From what I see at the moment there are two errors in stm32duino

  1. The script stm32CubeProg.sh has a problem:

https://github.com/stm32duino/Arduino_Tools/blob/d0ccf253d7109a4f79e37114f70f8f604c1262d6/stm32CubeProg.sh#L141

${STM32CP_CLI} -c port=${PORT} ${MODE} ${ERASE:+"-e all"} -q -d "${FILEPATH}" ${ADDRESS} "${OPTS}"

Instead it should be (‘-‘ instead of ‘+’):

${STM32CP_CLI} -c port=${PORT} ${MODE} ${ERASE:-"-e all"} -q -d "${FILEPATH}" ${ADDRESS} "${OPTS}"

Unfortunately, this will still not work, because the mass erase, issued by «-e all» will fail, which leads me to the second problem:

  1. Cube Programmer fails with mass erase «-e all» for the STMG031J6

The STM32G031J6 only has 32KB Flash ROM, however the Cube Programmer reports:

Chip ID: 0x466 
BootLoader protocol version: 3.1
Device name : STM32G03x/STM32G04x
Flash size  : 64 KBytes (default)
Device type : MCU
Revision ID : --  
Device CPU  : Cortex-M0+


Mass erase ... 

Error: Mass erase operation failed.

I assume that the cube programmer tries to erase 64KB which will fail, because only 32KB are available.

At this point we could modify this line:
https://github.com/stm32duino/Arduino_Tools/blob/d0ccf253d7109a4f79e37114f70f8f604c1262d6/stm32CubeProg.sh#L6
to
ERASE=»-e [0 15]»

But this will not make much sense, for other controllers. Applying a much bigger range to cover all STM controllers
ERASE=»-e [0 255]»
will work, but will also generate several errors.

@olikraus
olikraus

changed the title
Generic Board STM32G031J6, issues with starting the downloaded code (pinMode hangs)

Generic Board STM32G031J6, issues with starting the downloaded code (pinMode hangs) [Linux]

Feb 3, 2022

@olikraus



Copy link


Contributor

Author

I assume the problem is related to Linux only, because my problem was caused by an .sh script, which probably exists only on Linux machines.

@olikraus



Copy link


Contributor

Author

Ah, I was probably wrong with the Linux assumption. stm32CubeProg.sh will be executed via busybox also on windows, so I assume, that the same problem will appear also on windows machines.

@olikraus
olikraus

changed the title
Generic Board STM32G031J6, issues with starting the downloaded code (pinMode hangs) [Linux]

Generic Board STM32G031J6, issues with starting the downloaded code (pinMode hangs)

Feb 3, 2022

@olikraus



Copy link


Contributor

Author

I have created another issue for STM32CubeProgrammer, see stm32duino/Arduino_Tools#82

I think, this issue can be closed. Thanks a lot for your amazing support and providing STM32duino to the Arduino community.

@fpistm

Hi @olikraus
there is no issue with the script.

First by defaut the full erase is not request. It is a option added for some user which use the boards.local.txt or the platform.local.txt feature.

About the

1. The script stm32CubeProg.sh has a problem:

https://github.com/stm32duino/Arduino_Tools/blob/d0ccf253d7109a4f79e37114f70f8f604c1262d6/stm32CubeProg.sh#L141

${STM32CP_CLI} -c port=${PORT} ${MODE} ${ERASE:+"-e all"} -q -d "${FILEPATH}" ${ADDRESS} "${OPTS}"

Instead it should be (‘-‘ instead of ‘+’):

${STM32CP_CLI} -c port=${PORT} ${MODE} ${ERASE:-"-e all"} -q -d "${FILEPATH}" ${ADDRESS} "${OPTS}"

Unfortunately, this will still not work, because the mass erase, issued by «-e all» will fail, which leads me to the second problem:

${ERASE:+"-e all"} is the correct syntax in bash (See after). If ERASE is empty then null string else "-e all". Like the default protocol version is «1» and not «11» then erase all is not set.
image

@olikraus



Copy link


Contributor

Author

ok, I understand.

Anyhow, the problem is: If my code for STM32G031J6 changes in size, then the execution fails and requires a full (or at least suffient) erase, which does not happen at the moment.

The best solution would be, if I could enable full Flash erase (mass erase) operation for the STM32G031J6. Is there an option in the GUI already available for this? I think this applies to all STM32G031J6: Any upload will require a mass erase.

@fpistm

@olikraus



Copy link


Contributor

Author

set the protocol version to 11 instead of one will enable the full erase:

Thanks for the hint, I will try this.

I don’t think mass erase is required.

As mentioned above, the newly uploaded code to STM32G0 fails if the binary size was changed.
It is not neccesarily the mass erase, but there should be some good erease which allows reliable usage of STM32duino.
At least from myperspective my STM32G0 boards are not usable via STM32duino.
However, if a mass erase is executed before upload, then it seems to work without issues.

@fpistm

I’ve made the same setup than you and here the result:

      -------------------------------------------------------------------
                       STM32CubeProgrammer v2.9.0                  
      -------------------------------------------------------------------

Serial Port COM10 is successfully opened.
Port configuration: parity = even, baudrate = 115200, data-bit = 8,
                     stop-bit = 1.0, flow-control = off

Timeout error occured while waiting for acknowledgement.
Activating device: OK
Board       : --
Chip ID: 0x466 
BootLoader protocol version: 3.1
Device name : STM32G03x/STM32G04x
Flash size  : 64 KBytes (default)
Device type : MCU
Revision ID : --  
Device CPU  : Cortex-M0+


Mass erase ... 

Error: Mass erase operation failed.
Please verify flash protection


Memory Programming ...
Opening and parsing file: Blink.ino.bin
  File          : Blink.ino.bin
  Size          : 13720 Bytes
  Address       : 0x08000000 


Erasing memory corresponding to segment 0:
Erasing internal memory sectors [0 6]
Download in Progress:


File download complete
Time elapsed during download operation: 00:00:01.837

RUNNING Program ... 
  Address:      : 0x8000000
Start operation achieved successfully

Even if the mass erase failed, during the next step (programming) it first erases the 0-6 sectors and flash without any issue.
I’ve made several tests and sometimes it starts properly sometime not but in this case if reset the board then the program start properly.
About the binary size I don’t think it is the issue in any case your binary is less than 14kb —> 7 sectors of 2kb indicated as [0-6] in the erase steps.

@olikraus



Copy link


Contributor

Author

if reset the board then the program start properly.

This is exactly not the case. I change the size only by 4 bytes, then the flashed software becomes anusable. Also any reset does not help here. Let me repeat my problem:

  1. Switch into Bootloader Mode (BOOT0 Pin=high)
  2. Press reset to enter Bootloader USART Sync wait
  3. Full erase of flash memory (using an external tool stm32flash from sf.net)
  4. Press reset to again enter Bootloader USART Sync wait
  5. Upload the following code via Arduino IDE (USART, as discussed above)
#define MYPIN 6
// the setup function runs once when you press reset or power the board
void setup() {
  pinMode(MYPIN, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
  digitalWrite(MYPIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(200);
  digitalWrite(MYPIN, LOW);    // turn the LED off by making the voltage LOW
  delay(200);
}
  1. Change Boot0 pin to low
  2. Press reset: Blick starts as expected
  3. Change Boot0 pin to high
  4. Press reset: Blink stops, Bootloader enters USART sync
  5. I modify the delay from 200 to 300 (this will cause more bytes to be occupied, flash size becomes bigger)
#define MYPIN 6
// the setup function runs once when you press reset or power the board
void setup() {
  pinMode(MYPIN, OUTPUT);
}
// the loop function runs over and over again forever
void loop() {
  digitalWrite(MYPIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(300);
  digitalWrite(MYPIN, LOW);    // turn the LED off by making the voltage LOW
  delay(300);
}
  1. Upload of this code via Arduino IDE
  2. Change Boot0 pin to low
  3. Press reset: Nothing happens… and this is my problem

Erasing internal memory sectors [0 6]

I see the same message in both cases in the Arduino IDE, but still it doesen work.

14kb —> 7 sectors of 2kb indicated as [0-6]

I also assumed that one page is 2kb. However there is another miracle.
If I call the cube programmer CLI with «-e [0 31]» then the expectation would be that I get an error, because 32*2kb = 64kb, but the G031J6 only has 32 KB. However, «-e [0 31]» will NOT generate an error.
In fact «-e [0 33]» will generate an error only for sector 32 and 33. It looks like that cube programmer assumes 1kb as one page only.

However, if cube programmer assumes one page to be 1kb, then

Erasing internal memory sectors [0 6]

would only erase 7kb (out of the required 14 kb). Maybe cube programmer has a real problem, because it erases only half of the code. This would indeed explain why any code change will not work.

Maybe you can confirm the malfunction for the above 13 steps…

EDIT: Changed the delay values in the code

@fpistm

I’ve succeed to reproduce your issue sometimes after the reset, this is not regular and the board is in unknown step as event the STLink could not connect anymore.
I guess we had issues with CubeProgrammer and BL.
Anyway, with the same delay (200) I can have it working or not same with 1000.
If you flash the binary with the STLink it will works properly.

@olikraus



Copy link


Contributor

Author

I’ve succeed to reproduce your issue

I am happy to read this.

If you flash the binary with the STLink it will works properly.

I have not checked this, but if I do a full erase, then it will also work again.

Ok, I understand that I could use STLink.
However, let’s assume I want to continue with USART upload:
Do you see any chance to solve this within Arduino IDE?

From my perspective, if STM32duino would add «-e [0 31]» to the cube programmer cli as part of the upload arguments for the STM32G031J6, then the problem would be solved.

(again, as discussed, «-e all» does not work and also the GenG0.menu.upload_method.serialMethod.upload.protocol=11 trick will probably not work, because it just enables the none working «-e all»)

@fpistm

From my perspective, if STM32duino would add «-e [0 31]» to the cube programmer cli as part of the upload arguments for the STM32G031J6, then the problem would be solved.

Probably but it is just a workaround. You can use it using the platform.local.txt or the custom core as show in the wiki.

@olikraus



Copy link


Contributor

Author

Probably but it is just a workaround. You can use it using the platform.local.txt or the custom core as show in the wiki.

Sure, but i am also interessted in a more generic solution. The above problem will happen to everyone who uses STM32duino with the STM32G031J6, right? So it would be great if STM32duino could solve this problem somehow in the STM32duino project.

@fpistm

Probably. But I can’t be sure as it could depend of the bootloader version available within the mcu.
It could be also an issue with the STM32CubeProgrammer in that case a later version could solve the issue.

Changing the core to add «-e [0 31]» will impact all the generic G0 variants but it is probably not correct for all.

While I have not the exact reason why it fails, I would not deploy a fix as it could implies a lot of change in the core.
Please be patient 😉

@olikraus



Copy link


Contributor

Author

Changing the core to add «-e [0 31]» will impact all the generic G0 variants but it is probably not correct for all.

Very much correct. I also didn’t meant this as a generic solution. I think a generic solution should allow individual upload arguments for cube programmer cli based on the selected controller, so that J6 gets -e [0 31] and J4 might require -e [0 15].

While I have not the exact reason why it fails, I would not deploy a fix as it could implies a lot of change in the core.
Please be patient 😉

I am happy that you already guided me to find a workaround for my issue. At least I now know how to modify STM32duino so that it works with my board. Thats already a great success. Again: THANKS A LOT!

@fpistm

Changing the core to add «-e [0 31]» will impact all the generic G0 variants but it is probably not correct for all.

Very much correct. I also didn’t meant this as a generic solution. I think a generic solution should allow individual upload arguments for cube programmer cli based on the selected controller, so that J6 gets -e [0 31] and J4 might require -e [0 15].

Unfortunately, Arduino boards definition is very limited. So hard to do that or it would required to define all the boards at the same level with all the submenu duplicated 😉 This will lead to a boards.txt more than 100x longer and a very long menu …

@olikraus



Copy link


Contributor

Author

hmm.. I understand. So, it would be great if -e all would work….

@olikraus



Copy link


Contributor

Author

I tried to figure out whether CubeProgrammer works with 1kb or 2kb sector size. So I did the following test:

  1. Clear the flash

  2. Write 4000 bytes with value 4 to flash

  3. Execute -e [0 1] —> this should clear 4096 bytes if sectors are 2Kb

  4. Check whether all flash is cleared

  5. Clear and verify flash

./STM32_Programmer.sh -c port=/dev/ttyUSB0 -e [0 31]

./STM32_Programmer.sh -c port=/dev/ttyUSB0 -blankcheck
Flash memory blank checking...
Flash memory is empty.
  1. Write 4000x byte 4 to the flash
./STM32_Programmer.sh -c port=/dev/ttyUSB0 -fillmemory size=4000 pattern=4

The used start address is 0x08000000.
The used filling data size is 8 bits.
Filling memory operation:
  Start address           : 0x08000000
  Size(Bytes)             : 0x00000FA0
  Data value              : 0x00000004
  Filling data size(Bytes): 8 bits


Erasing internal memory sectors [0 1]

The filling memory operation achieved successfully

./STM32_Programmer.sh -c port=/dev/ttyUSB0 -blankcheck


Flash memory blank checking...

Warning: Flash memory is not empty at 0x08000000.

The warning is correct, the first none-empty byte is at 0x08000000

  1. Erase [0 1]
./STM32_Programmer.sh -c port=/dev/ttyUSB0 -e [0 1]
  1. Check the result
./STM32_Programmer.sh -c port=/dev/ttyUSB0 -blankcheck


Flash memory blank checking...

Warning: Flash memory is not empty at 0x08000800.

As a conclusion the «-e [0 1]» will only clear memory from 0 to 2047. This means the «-e» command expects sectors as 1kb size and indeed «-e [0 31]» is required to erase the complete flash of the STM32G031J6

During pattern flashing the output of cube programmer had been:

Erasing internal memory sectors [0 1]

This would make sense, if the erase sector size is 2kb. So at least, the input arguments to the -e command are different (1kb) to the generated output (2kb).

@olikraus



Copy link


Contributor

Author

I did another test:

  1. Write 4000 bytes with value 0x0f to 0x08000000
  2. Write 4000 bytes with value 0x55 to 0x08000000

Expectation would be, that I see 4000 bytes with value 0x55 0x08000000.
I will use the -fillmemory command of cube programmer for this, so here are the results:

  1. Initial clear of the memory to get a known state
./STM32_Programmer.sh -c port=/dev/ttyUSB0 -e [0 31]


./STM32_Programmer.sh -c port=/dev/ttyUSB0 -blankcheck

Flash memory is empty.
  1. Write the 0x0f pattern
./STM32_Programmer.sh -c port=/dev/ttyUSB0 -fillmemory size=4000 pattern=0x0f

The used start address is 0x08000000.
The used filling data size is 8 bits.
Filling memory operation:
  Start address           : 0x08000000
  Size(Bytes)             : 0x00000FA0
  Data value              : 0x0000000F
  Filling data size(Bytes): 8 bits


Erasing internal memory sectors [0 1]

The filling memory operation achieved successfully
  1. Read out 6000 bytes and show the content with «od» as hex data
./STM32_Programmer.sh -c port=/dev/ttyUSB0 -r 0x08000000 6000 tmp.bin && od -A x -t x1 tmp.bin


000000 0f 0f 0f 0f 0f 0f 0f 0f 0f 0f 0f 0f 0f 0f 0f 0f
*
000fa0 ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
*
001770

This looks very good, all is ok

  1. Write the 0x55 pattern
./STM32_Programmer.sh -c port=/dev/ttyUSB0 -fillmemory size=4000 pattern=0x55

The used start address is 0x08000000.
The used filling data size is 8 bits.
Filling memory operation:
  Start address           : 0x08000000
  Size(Bytes)             : 0x00000FA0
  Data value              : 0x00000055
  Filling data size(Bytes): 8 bits

Erasing internal memory sectors [0 1]

The filling memory operation achieved successfully
  1. Check whether the 0x55 has overwritten the 0x0f
./STM32_Programmer.sh -c port=/dev/ttyUSB0 -r 0x08000000 6000 tmp.bin && od -A x -t x1 tmp.bin

000000 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55
*
000800 0f 0f 0f 0f 0f 0f 0f 0f 0f 0f 0f 0f 0f 0f 0f 0f
*
000fa0 ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
*
001770

This is wrong. Only 2048 of the 4000 bytes with 0x055 had been written to the flash. Still we can see 0x0f values although we tried to overwrite these values.

Cube programmer is broken and does not work as expected for the fillmemory command.

I think the same wrong behavior applies to flash write command at least for the STM32G031J6.
STM32duino can not be used out of the box of the STM32G031J6 with USART interface.

@olikraus



Copy link


Contributor

Author

I executed the fillmemory test also with a STM32G031F8 device (64KB flash, USART interface) with the same wrong result.
Also «-e all» does not work
IMG_20220205_102831204_HDR

So, STM32G031F8 and STM32G031J6 are affected (unfortunately I do not have other STM32Gxxx devices for testing)

@olikraus



Copy link


Contributor

Author

I have tested the behavior with STM32G031F8 and SWD interface. Please excuse using a cheap stlink clone, but as a hobbyist, my budged doesn’t allow me to buy expensive equipment.

Results are good with SWD interface: «-e all» works as expected and also the the fillpattern command works as expected. Overwriting the 0x0f pattern with 0x55 correctly reports:

      -------------------------------------------------------------------
                        STM32CubeProgrammer v2.9.0                  
      -------------------------------------------------------------------

ST-LINK SN  : 220A030232124153354B4E00
ST-LINK FW  : V2J29S7
Board       : --
Voltage     : 3,16V
SWD freq    : 4000 KHz
Connect mode: Normal
Reset mode  : Software reset
Device ID   : 0x466
Revision ID : Rev 1.1
Device name : STM32G03x/STM32G04x
Flash size  : 64 KBytes
Device type : MCU
Device CPU  : Cortex-M0+
BL Version  : --


UPLOADING ...
  File          : tmp.bin
  Size          : 6000 Bytes
  Address:      : 0x8000000
Read progress:
[==================================================] 100% 
Data read successfully
Warning: The file tmp.bin already exists, it will be overwritten
Time elapsed during read operation is: 00:00:00.040
000000 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55 55
*
000fa0 ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff
*
001770

So it looks like Cube Programmer 2.9.0 has a problem with all STM32Gxxx devices connected via USART only (SWD works correctly).

IMG_20220205_104342092

@olikraus



Copy link


Contributor

Author

More remarks: The STM32G031Fx is not listed in STM32duino, probably I could use STM32G031Kx instead, but then the pin numbers might be different. Anyhow, just an observation.

@olikraus



Copy link


Contributor

Author

I tried to figure out how to change STM32duino so that the erase operation works correctly.
Unfortunately «-e all» just aborts with error and does not erase anything.
As a consequence your suggestion

set the protocol version to 11 instead of one will enable the full erase:

Does not work, because the «-e all» will not work at all for this device. So the only option to make the STMG032xx work correctly via USART flash is to modify stm32CubeProg.sh.

Summary

  • CubeProgrammer does not flash correctly via USART for several STM32G0xx (probably for all devices)
  • CubeProgrammer fails with error for the STM32G031J for «-e all»
  • There is (probably) no workaround in STM32duino to fix this via boards.txt or platform.txt. Instead modifing stm32CubeProg.sh seems to be the only option.

@fpistm

More remarks: The STM32G031Fx is not listed in STM32duino, probably I could use STM32G031Kx instead, but then the pin numbers might be different. Anyhow, just an observation.

You can add the generic quickly following the wiki to add a new board.

@fpistm

For the flash, based on the Ref Man, 2k page size is correct:
image

image

We will check with STM32CubeProgrammer about this issue and I agree that a fix could only be done in the script. I’ve already think about that but waiting some internal feedback.

@olikraus



Copy link


Contributor

Author

We will check with STM32CubeProgrammer about this issue and I agree that a fix could only be done in the script. I’ve already think about that but waiting some internal feedback.

Thanks!

@ABOSTM

@ABOSTM

@olikraus,
I found 2 issues that prevent proper execution of application after UART Bootloader.
I proposed a fix: #1653
It works for me, (no need for a full erase)

@olikraus



Copy link


Contributor

Author

I am a little bit confused regarding closing this topic: #1653 will solve the automatic startup after download (USER_VECT_TAB_ADDRESS and clock setup topics).
However the CubeProgrammer is broken from my perspective and will not allow a proper upload via USART of the code length has changed.

I mean this issue has described two issues and only one is now solved by #1653

How shell we deal with the USART flash problems? Any progress on your Internal Ticket 122350?

@ABOSTM

From my point of view, yes, this issue is closed:
Everything works on my side thanks to both fixes.
The internal Ticket 122350 concerns Mass erase. Despite issue is still there (it is not closed internally),
Mass erase is not needed once both fixes are present. (So in the context of Arduino this is closed)

The issue that upload via UART is broken when code length changes, is I think invalid (or miss interpretation). I have not seen evidences that links code length change and bootloader issue. And this is not something I observed during my analysis.
And finally once I have both fixes integrated, I face no issue.
I presume this was a side effect of both issues I fixed.

Now if you still have some issues using UART bootlader despites the fixes I made, then I propose to open a new issue, and in any case, experiments should be restarted from scratch with both fixes.

@olikraus



Copy link


Contributor

Author

Now if you still have some issues using UART bootlader despites the fixes I made, then I propose to open a new issue, and in any case, experiments should be restarted from scratch with both fixes.

I agree, this makes sense.

@olikraus



Copy link


Contributor

Author

The problem mentioned on 3 Feb seems to be resolved now with CubeProgrammer 2.10

Thanks to all!

@CSV-12

@olikraus Looks like you solved the problem, but I’m wondering about that resistor value in series with the LED. Typically these are 1.7V and power supply is at 3.3V so the 100 Ohm resistor will drop 1.6V pulling the max current of 16mA from the MCU pin.
Maybe not a happy value?

table19

@olikraus



Copy link


Contributor

Author

In fact the resistor is not required. The MCU will limit the current to the specified value from the datasheet: you can connect a LED directly to any of the pins.

@CSV-12

Great!

I see a «20mA» condition in Table 53, but nothing about current limiting. Table 19 above is from paragraph 5.2, «Absolute maximum ratings».

An active current limiting would involve more on-die parts that would measure current and turn off at a threshold value, allowing short to ground and to VCC which is also mentioned in the data sheet.

Where did you find «_The MCU will limit the current to the specified value from the datashee_t» ??

@olikraus



Copy link


Contributor

Author

The current limitation is an effect/ characteristics of the underlaying CMOS technology. It doesn’t require any extra parts. Unlike TTL logic a CMOS transistor has still a significant resistance if the transistor is fully turned on (So called on-resistance of the MOS transistor). This «build in» resistance will always limit the output current.

@CSV-12

Apply Ohm’s Law to that FET’s RDS-on and you will soon exceed what a MCU port can handle. 0.020mA*3.3V=0.066W.
Some LEDs will increase its contact potential enough as as current goes up, and possibly reach an tolerable equilibrium, in the best cases. Overloading a IO pin can in worst cases lead to erratic behavior. Shorting a port pin to ground will quickly lead to a failure. Not worth the risk.
Your assertion is not based on facts.

@olikraus



Copy link


Contributor

Author

Apply Ohm’s Law to that FET’s RDS-on and you will soon exceed what a MCU port can handle. 0.020mA*3.3V=0.066W.

Each FET has a kind of a lowest RDS-on. This will limit the current. Of course the FET may still get destroyed if RDS on is very low and no proper cooling is applied. And yes: for an MCU you can not expect all GPIOs to deliver 20mA: There is an upper limit of what the overall MCU can deliver (this is also mentioned in the MCU datasheet).

Moreover your calculation is wrong, because you need to multiple the current with the voltage over the enabled output FET of the driver stage of the GPIO of the uC. This, however, is the applied power voltage minus the forward voltage of your LED: 0.020mA * (3.3V-1.8V)

Your assertion is not based on facts.

Just to clarify this. I was talking about a single GPIO pin.

Regarding facts, you could look at this FET: https://eu.mouser.com/datasheet/2/196/Infineon_BSS127I_DataSheet_v02_01_EN-2237807.pdf
It can only deliver 21mA (comparable to a typical uC output) and diagrams 5 and 6 clearly show, that the output current is limited.
According to diagramm 6, RDS-on is at least 280 Ohm (estimated from the diagramm).
If we assume Vds as 3.3V and a forward voltage of your 20mA LED of 1.8V, then we have: (3.3V-1.8V)/280Ohm = 5.3mA
So you can add your LED without problem and without additional resistor. In fact LED will not be at max brightness, because 5.3mA is still much lower than 20mA.

Recently I lost power on my printer with an BTT SKR 2 board (https://github.com/bigtreetech/SKR-2). I connected my ST-Link v3 to the SWD pins and confirmed I can identify the IC. I am connecting to the device with SWD mode, 8KHz frequency, Connect under reset, and hardware reset mode. I have shorted BOOT0 to VCC and BOOT1 to ground.

When attempting to read/write, STM32CubeProgrammer states «data read failed, verify flash protection». When checking the RDP option byte, it is set to 0xFF instead of the normal 0xAA, 0xBB, or 0xCC. When attempting to change the readout protection, it is not successful. I have attached logs below.

Initial Connection

  11:48:16:281 : ST-LINK SN  : *removed*
  11:48:16:281 : ST-LINK FW  : V3J9M3B5S1
  11:48:16:282 : Board       : STLINK-V3SET
  11:48:16:283 : Voltage     : 3.25V
  11:48:16:288 : SWD freq    : 8000 KHz
  11:48:16:288 : Connect mode: Under Reset
  11:48:16:288 : Reset mode  : Hardware reset
  11:48:16:290 : Device ID   : 0x419
  11:48:16:291 : Revision ID : Rev 5/B
  11:48:16:297 : Reading data...
  11:48:16:298 : r ap 0 @0x40023C14 0x00000004 bytes Data 0xCFFFFFFD
  11:48:16:298 : Reading data...
  11:48:16:299 : r ap 0 @0x40023C14 0x00000004 bytes Data 0xCFFFFFFD
  11:48:16:299 : Reading data...
  11:48:16:300 : r ap 0 @0x1FFF7A22 0x00000004 bytes Data 0x0000CFFF
  11:48:16:800 : r ap 0 @0x1FFF7A22 0x00000004 bytes Data 0x00000000
  11:48:16:800 : Database: Config 1 is active.
  11:48:16:802 : flash loader C:Program FilesSTMicroelectronicsSTM32CubeSTM32CubeProgrammerbin/FlashLoader/0x419.stldr is loaded
  11:48:16:802 : Reading data...
  11:48:16:802 : r ap 0 @0x1FFF7A22 0x00000004 bytes Data 0x00000000
  11:48:17:302 : r ap 0 @0x1FFF7A22 0x00000004 bytes Data 0x00000000
  11:48:17:302 : failed to read the requested memory content
  11:48:17:304 : r ap 0 @0x1FFF76DE 0x00000004 bytes Data 0xAFBB0000
  11:48:17:304 : fail @0x00000001
  11:48:17:403 : UPLOADING OPTION BYTES DATA ...
  11:48:17:404 :   Bank          : 0x00
  11:48:17:404 :   Address       : 0x40023c14
  11:48:17:404 :   Size          : 8 Bytes
  11:48:17:404 : Reading data...
  11:48:17:404 : r ap 0 @0x40023C14 0x00000008 bytes Data 0xCFFFFFFD
  11:48:17:404 : UPLOADING OPTION BYTES DATA ...
  11:48:17:404 :   Bank          : 0x00
  11:48:17:405 :   Address       : 0x40023c14
  11:48:17:405 :   Size          : 8 Bytes
  11:48:17:405 : Reading data...
  11:48:17:405 : r ap 0 @0x40023C14 0x00000008 bytes Data 0xCFFFFFFD
  11:48:17:413 : r ap 0 @0x1FFF76DE 0x00000004 bytes Data 0xAFBB0FFF
  11:48:17:414 : fail @0x00000001
  11:48:17:414 : UPLOADING ...
  11:48:17:414 :   Size          : 1024 Bytes
  11:48:17:414 :   Address       : 0x8000000
  11:48:17:414 : Read progress:
  11:48:17:414 : Reading data...
  11:48:17:414 : r ap 0 @0x08000000 0x00000400 bytes Data 0x00000080
  11:48:17:899 : r ap 0 @0x08000000 0x00000400 bytes Data 0x00000011
  11:48:17:899 : Error: Data read failed
  11:48:17:958 : r ap 0 @0x1FFF76DE 0x00000004 bytes Data 0xAFBB0000
  11:48:17:958 : fail @0x00000001
  11:48:18:901 : r ap 0 @0x1FFF76DE 0x00000004 bytes Data 0xAFBB2003
  11:48:18:901 : fail @0x00000001
  11:48:19:904 : r ap 0 @0x1FFF76DE 0x00000004 bytes Data 0xAFBB2003
  11:48:19:904 : fail @0x00000001

Option Byte Attempt

  11:40:11 : ST-LINK SN  : *removed*
  11:40:11 : ST-LINK FW  : V3J9M3B5S1
  11:40:11 : Board       : STLINK-V3SET
  11:40:11 : Voltage     : 3.25V
  11:40:11 : SWD freq    : 8000 KHz
  11:40:11 : Connect mode: Under Reset
  11:40:11 : Reset mode  : Hardware reset
  11:40:11 : Device ID   : 0x419
  11:40:11 : Revision ID : Rev 5/B
  11:40:12 : UPLOADING OPTION BYTES DATA ...
  11:40:12 :   Bank          : 0x00
  11:40:12 :   Address       : 0x40023c14
  11:40:12 :   Size          : 8 Bytes
  11:40:12 : UPLOADING ...
  11:40:12 :   Size          : 1024 Bytes
  11:40:12 :   Address       : 0x8000000
  11:40:12 : Read progress:
  11:40:13 : Error: Data read failed
  11:40:19:271 : Option byte command : -ob  RDP=170 
  11:40:19:274 : PROGRAMMING OPTION BYTES AREA ...
  11:40:19:274 : Reading data...
  11:40:19:275 : r ap 0 @0x40023C14 0x00000004 bytes Data 0xCFFFFFFD
  11:40:19:275 : Reading data...
  11:40:19:275 : r ap 0 @0x40023C14 0x00000004 bytes Data 0xCFFFFFFD
  11:40:19:275 : Reading data...
  11:40:19:275 : r ap 0 @0x1FFF7A22 0x00000004 bytes Data 0x0000CFFF
  11:40:19:775 : r ap 0 @0x1FFF7A22 0x00000004 bytes Data 0x00000000
  11:40:19:775 : Database: Config 1 is active.
  11:40:19:775 :   Bank          : 0x00
  11:40:19:776 :   Address       : 0x40023c14
  11:40:19:776 :   Size          : 8 Bytes
  11:40:19:776 : OB buffer: fdaaffcf0000ff0f
  11:40:19:776 : Buffer program...
  11:40:19:783 : halt ap 0 
  11:40:19:783 : w ap 0 reg 15 PC   (0x20000000)  
  11:40:19:783 : w ap 0 reg 17 MSP  (0x20000500)  
  11:40:19:784 : w ap 0 reg 16 xPSR (0x01000000)  
  11:40:19:784 : w ap 0 @0x20001160 0x00000200 bytes Data 0x00000000
  11:40:19:784 : w ap 0 @0x20000000 0x00000004 bytes Data 0x0000BE00
  11:40:19:790 : w ap 0 @0x20000004 0x00000D38 bytes Data 0xF000B580
  11:40:19:791 : w ap 0 @0x20001160 0x00000008 bytes Data 0xCFFFAAFD
  11:40:19:791 : Loader write option bytes...
  11:40:19:791 : Init flashloader...
  11:40:19:791 : halt ap 0 
  11:40:19:791 : w ap 0 reg 0 R0   0x00000001
  11:40:19:791 : w ap 0 reg 1 R1   0x00000000
  11:40:19:792 : w ap 0 reg 2 R2   0x00000000
  11:40:19:792 : w ap 0 reg 3 R3   0x00000000
  11:40:19:792 : w ap 0 reg 4 R4   0x00000000
  11:40:19:798 : w ap 0 reg 5 R5   0x00000000
  11:40:19:798 : w ap 0 reg 6 R6   0x00000000
  11:40:19:798 : w ap 0 reg 7 R7   0x00000000
  11:40:19:800 : w ap 0 reg 8 R8   0x00000000
  11:40:19:800 : w ap 0 reg 9 R9   0x00000000
  11:40:19:804 : w ap 0 reg 10 R10  0x00000000
  11:40:19:805 : w ap 0 reg 11 R11  0x00000000
  11:40:19:806 : w ap 0 reg 12 R12  0x00000000
  11:40:19:806 : w ap 0 reg 13 SP   0x00000000
  11:40:19:807 : w ap 0 reg 14 LR   0x20000001
  11:40:19:808 : w ap 0 reg 15 PC   0x20000005
  11:40:19:808 : w ap 0 reg 16 xPSR 0x01000000
  11:40:19:809 : w ap 0 reg 17 MSP  0x20001138
  11:40:19:809 : w ap 0 reg 18 PSP  0x00000000
  11:40:19:809 : run ap 0 
  11:40:19:809 : halt ap 0 
  11:40:19:809 : r ap 0 reg 0 R0   0x00000001
  11:40:19:809 : w ap 0 reg 0 R0   0x40023C14
  11:40:19:810 : w ap 0 reg 1 R1   0x00000008
  11:40:19:810 : w ap 0 reg 2 R2   0x20001160
  11:40:19:810 : w ap 0 reg 3 R3   0x00000002
  11:40:19:811 : w ap 0 reg 4 R4   0x00000000
  11:40:19:811 : w ap 0 reg 5 R5   0x00000000
  11:40:19:811 : w ap 0 reg 6 R6   0x00000000
  11:40:19:812 : w ap 0 reg 7 R7   0x00000000
  11:40:19:812 : w ap 0 reg 8 R8   0x00000000
  11:40:19:812 : w ap 0 reg 9 R9   0x00000000
  11:40:19:812 : w ap 0 reg 10 R10  0x00000000
  11:40:19:812 : w ap 0 reg 11 R11  0x00000000
  11:40:19:813 : w ap 0 reg 12 R12  0x00000000
  11:40:19:813 : w ap 0 reg 13 SP   0x00000000
  11:40:19:815 : w ap 0 reg 14 LR   0x20000001
  11:40:19:815 : w ap 0 reg 15 PC   0x200000AB
  11:40:19:819 : w ap 0 reg 16 xPSR 0x01000000
  11:40:19:821 : w ap 0 reg 17 MSP  0x20001138
  11:40:19:822 : w ap 0 reg 18 PSP  0x00000000
  11:40:19:822 : run ap 0 
  11:40:23:139 : UPLOADING OPTION BYTES DATA ...
  11:40:23:139 :   Bank          : 0x00
  11:40:23:139 :   Address       : 0x40023c14
  11:40:23:139 :   Size          : 8 Bytes
  11:40:23:139 : Reading data...
  11:40:23:139 : r ap 0 @0x40023C14 0x00000008 bytes Data 0xCFFFFFFD
  11:40:23:140 : OPTION BYTE PROGRAMMING VERIFICATION:
  11:40:23:140 : Error: Expected value for Option Byte "RDP": 0xAA, found: 0xFF
  11:40:23:156 : Error: Option Byte Programming failed
  11:40:23:173 : Reading data...
  11:40:23:175 : r ap 0 @0x40023C14 0x00000004 bytes Data 0xCFFFFFFD
  11:40:23:176 : Reading data...
  11:40:23:177 : r ap 0 @0x40023C14 0x00000004 bytes Data 0xCFFFFFFD
  11:40:23:177 : Reading data...
  11:40:23:178 : r ap 0 @0x1FFF7A22 0x00000004 bytes Data 0x0000CFFF
  11:40:23:641 : r ap 0 @0x1FFF7A22 0x00000004 bytes Data 0x00000000
  11:40:23:641 : Database: Config 1 is active.
  11:40:23:641 : Time elapsed during option Bytes configuration: 00:00:04.368
  11:40:23:676 : UPLOADING OPTION BYTES DATA ...
  11:40:23:676 :   Bank          : 0x00
  11:40:23:676 :   Address       : 0x40023c14
  11:40:23:676 :   Size          : 8 Bytes
  11:40:23:677 : Reading data...
  11:40:23:677 : r ap 0 @0x40023C14 0x00000008 bytes Data 0xCFFFFFFD

Full Chip Erase Attempt

  12:11:30:295 : ST-LINK SN  : *removed*
  12:11:30:295 : ST-LINK FW  : V3J9M3B5S1
  12:11:30:296 : Board       : STLINK-V3SET
  12:11:30:296 : Voltage     : 3.25V
  12:11:30:300 : SWD freq    : 8000 KHz
  12:11:30:300 : Connect mode: Under Reset
  12:11:30:300 : Reset mode  : Hardware reset
  12:11:30:304 : Device ID   : 0x419
  12:11:30:305 : Revision ID : Rev 5/B
  12:11:30:311 : Reading data...
  12:11:30:312 : r ap 0 @0x40023C14 0x00000004 bytes Data 0xCFFFFFFD
  12:11:30:312 : Reading data...
  12:11:30:313 : r ap 0 @0x40023C14 0x00000004 bytes Data 0xCFFFFFFD
  12:11:30:313 : Reading data...
  12:11:30:313 : r ap 0 @0x1FFF7A22 0x00000004 bytes Data 0x0000CFFF
  12:11:30:813 : r ap 0 @0x1FFF7A22 0x00000004 bytes Data 0x00000000
  12:11:30:813 : Database: Config 1 is active.
  12:11:30:817 : flash loader C:Program FilesSTMicroelectronicsSTM32CubeSTM32CubeProgrammerbin/FlashLoader/0x419.stldr is loaded
  12:11:30:817 : Reading data...
  12:11:30:818 : r ap 0 @0x1FFF7A22 0x00000004 bytes Data 0x00000000
  12:11:31:317 : r ap 0 @0x1FFF7A22 0x00000004 bytes Data 0x00000000
  12:11:31:317 : failed to read the requested memory content
  12:11:31:318 : r ap 0 @0x1FFF76DE 0x00000004 bytes Data 0xAFAE0000
  12:11:31:318 : fail @0x00000001
  12:11:31:372 : UPLOADING OPTION BYTES DATA ...
  12:11:31:372 :   Bank          : 0x00
  12:11:31:372 :   Address       : 0x40023c14
  12:11:31:372 :   Size          : 8 Bytes
  12:11:31:373 : Reading data...
  12:11:31:373 : r ap 0 @0x40023C14 0x00000008 bytes Data 0xCFFFFFFD
  12:11:31:373 : UPLOADING OPTION BYTES DATA ...
  12:11:31:373 :   Bank          : 0x00
  12:11:31:373 :   Address       : 0x40023c14
  12:11:31:373 :   Size          : 8 Bytes
  12:11:31:373 : Reading data...
  12:11:31:373 : r ap 0 @0x40023C14 0x00000008 bytes Data 0xCFFFFFFD
  12:11:31:382 : r ap 0 @0x1FFF76DE 0x00000004 bytes Data 0xAFAE0FFF
  12:11:31:382 : fail @0x00000001
  12:11:31:382 : UPLOADING ...
  12:11:31:382 :   Size          : 1024 Bytes
  12:11:31:382 :   Address       : 0x8000000
  12:11:31:382 : Read progress:
  12:11:31:383 : Reading data...
  12:11:31:383 : r ap 0 @0x08000000 0x00000400 bytes Data 0x00000080
  12:11:31:869 : r ap 0 @0x08000000 0x00000400 bytes Data 0x00000011
  12:11:31:869 : Error: Data read failed
  12:11:31:933 : r ap 0 @0x1FFF76DE 0x00000004 bytes Data 0xAFAE0000
  12:11:31:933 : fail @0x00000001
  12:11:32:871 : r ap 0 @0x1FFF76DE 0x00000004 bytes Data 0xAFAE2003
  12:11:32:871 : fail @0x00000001
  12:11:33:874 : r ap 0 @0x1FFF76DE 0x00000004 bytes Data 0xAFAE2003
  12:11:33:874 : fail @0x00000001
  12:11:34:876 : r ap 0 @0x1FFF76DE 0x00000004 bytes Data 0xAFAE2003
  12:11:34:876 : fail @0x00000001
  12:11:35:878 : r ap 0 @0x1FFF76DE 0x00000004 bytes Data 0xAFAE2003
  12:11:35:878 : fail @0x00000001
  12:11:36:394 : MASS ERASE ... 
  12:11:36:396 : halt ap 0 
  12:11:36:396 : r ap 0 reg 15 PC   0xFFFFFFFE
  12:11:36:396 : PC value=fffffffe  : 
  12:11:36:396 : Flash erase...
  12:11:36:406 : halt ap 0 
  12:11:36:406 : w ap 0 reg 15 PC   (0x20000000)  
  12:11:36:406 : w ap 0 reg 17 MSP  (0x20000500)  
  12:11:36:407 : w ap 0 reg 16 xPSR (0x01000000)  
  12:11:36:407 : w ap 0 @0x20001160 0x00000200 bytes Data 0x00000000
  12:11:36:407 : w ap 0 @0x20000000 0x00000004 bytes Data 0x0000BE00
  12:11:36:411 : w ap 0 @0x20000004 0x00000D38 bytes Data 0xF000B580
  12:11:36:411 : Init flashloader...
  12:11:36:412 : halt ap 0 
  12:11:36:412 : w ap 0 reg 0 R0   0x00000001
  12:11:36:412 : w ap 0 reg 1 R1   0x00000000
  12:11:36:413 : w ap 0 reg 2 R2   0x00000000
  12:11:36:416 : w ap 0 reg 3 R3   0x00000000
  12:11:36:416 : w ap 0 reg 4 R4   0x00000000
  12:11:36:416 : w ap 0 reg 5 R5   0x00000000
  12:11:36:417 : w ap 0 reg 6 R6   0x00000000
  12:11:36:417 : w ap 0 reg 7 R7   0x00000000
  12:11:36:418 : w ap 0 reg 8 R8   0x00000000
  12:11:36:419 : w ap 0 reg 9 R9   0x00000000
  12:11:36:419 : w ap 0 reg 10 R10  0x00000000
  12:11:36:420 : w ap 0 reg 11 R11  0x00000000
  12:11:36:420 : w ap 0 reg 12 R12  0x00000000
  12:11:36:421 : w ap 0 reg 13 SP   0x00000000
  12:11:36:421 : w ap 0 reg 14 LR   0x20000001
  12:11:36:421 : w ap 0 reg 15 PC   0x20000005
  12:11:36:421 : w ap 0 reg 16 xPSR 0x01000000
  12:11:36:421 : w ap 0 reg 17 MSP  0x20001138
  12:11:36:421 : w ap 0 reg 18 PSP  0x00000000
  12:11:36:421 : run ap 0 
  12:11:36:422 : halt ap 0 
  12:11:36:422 : r ap 0 reg 0 R0   0x00000001
  12:11:36:422 : Loader mass erase...
  12:11:36:422 : w ap 0 reg 0 R0   0x00000002
  12:11:36:423 : w ap 0 reg 1 R1   0x00000000
  12:11:36:423 : w ap 0 reg 2 R2   0x00000000
  12:11:36:424 : w ap 0 reg 3 R3   0x00000000
  12:11:36:424 : w ap 0 reg 4 R4   0x00000000
  12:11:36:428 : w ap 0 reg 5 R5   0x00000000
  12:11:36:429 : w ap 0 reg 6 R6   0x00000000
  12:11:36:429 : w ap 0 reg 7 R7   0x00000000
  12:11:36:429 : w ap 0 reg 8 R8   0x00000000
  12:11:36:430 : w ap 0 reg 9 R9   0x00000000
  12:11:36:431 : w ap 0 reg 10 R10  0x00000000
  12:11:36:431 : w ap 0 reg 11 R11  0x00000000
  12:11:36:431 : w ap 0 reg 12 R12  0x00000000
  12:11:36:432 : w ap 0 reg 13 SP   0x00000000
  12:11:36:432 : w ap 0 reg 14 LR   0x20000001
  12:11:36:433 : w ap 0 reg 15 PC   0x20000217
  12:11:36:433 : w ap 0 reg 16 xPSR 0x01000000
  12:11:36:434 : w ap 0 reg 17 MSP  0x20001138
  12:11:36:435 : w ap 0 reg 18 PSP  0x00000000
  12:11:36:435 : run ap 0 
  12:11:36:437 : halt ap 0 
  12:11:36:437 : r ap 0 reg 0 R0   0x00000000
  12:11:36:437 : Error: Mass erase operation failed.Please verify flash protection
  12:11:36:454 : r ap 0 @0x1FFF76DE 0x00000004 bytes Data 0xAFAE0000
  12:11:36:455 : fail @0x00000001
  12:11:37:425 : r ap 0 @0x1FFF76DE 0x00000004 bytes Data 0xAFAE2003
  12:11:37:425 : fail @0x00000001
  12:11:38:428 : r ap 0 @0x1FFF76DE 0x00000004 bytes Data 0xAFAE2003
  12:11:38:428 : fail @0x00000001
  12:11:39:431 : r ap 0 @0x1FFF76DE 0x00000004 bytes Data 0xAFAE2003
  12:11:39:431 : fail @0x00000001

I have tried all the variations of BOOT0/BOOT1 configurations, as well as attempting to use STLink Utility. Is there any other way to recover this MCU before condemning it?

Понравилась статья? Поделить с друзьями:
  • Error maskrom must choose loader for erasing перевод
  • Error marker find the markers
  • Error mapping types
  • Error manifest merger failed with multiple errors see logs
  • Error management culture