1. Use environment

Article Directory
Use SREC_CAT to convert the bin file into a SREC file
One of the things missing for Embedded in the GNU linker is that it cannot generate a CRC checksum. Luckily, there is the solution of using SRecord:
<img loading="lazy" aria-describedby="caption-attachment-14792" data-attachment-id="14792" data-permalink="https://mcuoneclipse.com/2015/04/26/crc-checksum-generation-with-srecord-tools-for-gnu-and-eclipse/srecord-1-64-web-page/" data-orig-file="https://mcuoneclipse.files.wordpress.com/2015/04/srecord-1-64-web-page.png" data-orig-size="1018,602" data-comments-opened="1" data-image-meta="{"aperture":"0","credit":"","camera":"","caption":"","created_timestamp":"0","copyright":"","focal_length":"0","iso":"0","shutter_speed":"0","title":"","orientation":"0"}" data-image-title="SRecord 1.64 Web Page" data-image-description="
SRecord 1.64 Web Page
” data-image-caption=”
SRecord 1.64 Web Page
” data-medium-file=”https://mcuoneclipse.files.wordpress.com/2015/04/srecord-1-64-web-page.png?w=300″ data-large-file=”https://mcuoneclipse.files.wordpress.com/2015/04/srecord-1-64-web-page.png?w=584″ src=”https://mcuoneclipse.files.wordpress.com/2015/04/srecord-1-64-web-page.png?w=584&h=345″ alt=”SRecord 1.64 Web Page” srcset=”https://mcuoneclipse.files.wordpress.com/2015/04/srecord-1-64-web-page.png?w=584&h=345 584w, https://mcuoneclipse.files.wordpress.com/2015/04/srecord-1-64-web-page.png?w=150&h=89 150w, https://mcuoneclipse.files.wordpress.com/2015/04/srecord-1-64-web-page.png?w=300&h=177 300w, https://mcuoneclipse.files.wordpress.com/2015/04/srecord-1-64-web-page.png?w=768&h=454 768w, https://mcuoneclipse.files.wordpress.com/2015/04/srecord-1-64-web-page.png 1018w” sizes=”(max-width: 584px) 100vw, 584px”>
SRecord 1.64 Web Page
1 Introduction
Embedded firmware is generally divided into BootLoader and App. BootLoader is used to start verification, App upgrade, App version rollback and other functions. BootLoader runs in the first stage of CPU power on, and then jumps to the App address to execute the application. Therefore, when the firmware is released, there will be BootLoader firmware and App firmware; at this time, we expect to merge the BootLoader firmware and App firmware into one firmware, so that it only needs to be burned once in mass production.
CRC_To_HEX_Py
Скрипт предназначен для вставки контрольной суммы CRC16 в конец hex файла прошивки для последующего самотестирования кода во FLASH памяти микроконтроллера.
Скрипт создан для среды разработки STM32CubeIDE.
Проект, который являлся исходным материалом для данного скрипта: https://github.com/ethanhuanginst/STM32CubeIDE-Workshop-2019/tree/master/hands-on/06_F746-DISCO-CRC
Подготовка (для Windows)
- Скачать и установить интерпретатор Python3 (при установке доабвить исполняемый файл python в переменную среды Path);
- Разместить файл crc_to_hex.py и srec_cat.exe в корневом каталоге проекта STM32CubeIDE;
Настройка выполнения скрипта
- Открыть проект STM32CubeIDE;
- Нажать правой кнопкой мыши на проект и выбрать Propierties;
- Открыть раздел C/C++ Build->Settings вкладка Build Steps;
- В поле “Command:” раздела “Post-build steps” вписать строку:
python ../crc_to_hex.py "${ProjName}.hex" "${ProjName}_CRC.hex"

Далее после компиляции проекта будет создаваться Hex файл прошивки с контрольной суммой в конце.
Настройка загрузки Hex файла с контрольной суммой при отладке
- Создать отладочную конфигурацию и зайти в раздел Startup;
- В поле Load Image and Symbols необходимо добавить новую строку с настройкой на Hex файл с контрольной суммой;
- Далее настройки произвести как на примере ниже:

Алгоритм вычисления CRC16 программой srec_cat
Используемый полином: 0x1021
Начальное значение контрольной суммы: 0x1D0F
Функция на Си:
<div data-snippet-clipboard-copy-content="uint16_t Crc16(uint8_t *pcBlock, uint32_t len)
{
uint16_t crc = 0x1D0F;
uint8_t i;
while (len–)
{
crc ^= *pcBlock++ << 8;
for (i = 0; i < 8; i++)
crc = crc & 0x8000 ? (crc << 1) ^ 0x1021 : crc <
uint16_t Crc16(uint8_t *pcBlock, uint32_t len)
{
uint16_t crc = 0x1D0F;
uint8_t i;
while (len--)
{
crc ^= *pcBlock++ << 8;
for (i = 0; i < 8; i++)
crc = crc & 0x8000 ? (crc << 1) ^ 0x1021 : crc << 1;
}
return crc;
}
С приходом тепла вновь ощутил ущербность программистов родного автоваза. Машина брыкается, с места трогается с провалами и рывками, электронная педаль газа реагирует с секундной задержкой, и даже когда до машины доходит, что педаль газа была нажата, то разгон получается такой, будто под тобой не 106 лошадей, а один жирный увалень, которого как ни бей – ногами он быстрее перебирать не станет. А уж если в него ещё и 92 бензин залить, то ситуация ещё сильнее усугубится, и даже музыка не сможет заглушить звона от детонации. Впрочем многие на это не обращают внимание, а кто-то с подобными проблемами вовсе не сталкивался – автоваз одинаковых машин не выпускает.

Впрочем и я уже с проблемой смирился. Но на днях участник форума xrayclub под ником Electromaster выложил ссылку на свой пост на drive2, после прочтения которого появилась новая надежда. Сразу же обратился за помощью к пользователю msa96.
Сходу он никого не смог порекомендовать в нашем городе, но предложил произвести прошивку самостоятельно, порекомендовав товарища, который и помог работаться с процессом прошивки. Собственно это была небольшая предыстория, а ниже будет описан сам процесс прошивки ЭБУ на примере М86 Итэлма.

Первым делом нужно посмотреть, сколько стоит новый блок управления двигателем и сравнить его цену со стоимостью прошивки в сервисе. Мне не известно, насколько хорошо блок защищён от дурака, и возможно, что достаточно будет перепутать плюс с минусом и блок можно будет отправлять в ремонт.
Кроме того, если при прошивке что-то пойдёт не так, то опять же можно потерять блок или возможность его прошивать данным методом. Но в целом процесс довольно простой, не требует особых знаний, а из железа потребуется только USB-K-Line адаптер, 12В блок питания и несколько проводов, чтобы соединить всё это вместе.

В моём случае в качестве адаптера оказался usb vag com kkl 409.1 на чипе CH340. И чтобы там не рассказывали маркетолухи, в данном случае не имеет никакого значения, будет адаптер выполнен с использованием usb-uart преобразователя от фирмы FTDI, или его аналоге – CH340.
Главное, чтобы адаптер определился в системе как COM-порт. В случае проблем с установкой драйверов, можно попробовать установить их вручную (например для CH340).

Собственное потребление контроллера М86 (без подключенных к нему устройств) составляет примерно 1Вт, поэтому подойдёт любой блок питания на 12В. Данное питание так же потребуется подключить и к K-Line адаптеру, так как при штатном использовании он предполагает получение питания от бортовой сети автомобиля через OBD2 разъём.
Чтобы немного упростить задачу и избавиться от необходимости использовать внешний блок питания, я решил встроить в адаптер повышающий dc-dc преобразователь на базе MT3608. Мощности данного преобразователя достаточно как для питания адаптера, так и для питания ЭБУ. А размеры позволяют разместить его внутри корпуса адаптера.

К блоку управления потребуется подцепить 5 проводов, я использовал китайские монтажные провода (dupont wire).
Плюс 12В на L3 (питание ЭБУ), на A5 (зажигание), и на G5 (переключение контроллера в режим программирования). Так же +12В подключается к адаптеру на пин 16.
Минусовой провод GND – L4 на блоке соединяется с минусом на адаптере – пин 4, и с минусом блока питания.
И так же K-Line – пин C4 (на правом разъёме) соединяем с пином 7 адаптера.
При подключении стоит быть аккуратным, и не замыкать провода на соседние пины, так как например пины L3 и K3 соединены, и подав +12В на один, они окажутся на втором. Аналогично с землёй – K4 K5 L4 L5 – это один и тот же провод.


Тыкаем: New -> Create a new target configuration step by step. Далее

Заполняем Taget description: “XC2768X-136F”, выбираем в Family: SAB C166S-V2 Family (XC16x, XC2000, XE166). Далее

В type выбираем XC2768X-136F. Далее

Выбираем Minimonitor Interface. Нажимаем Setup

На вкладке General в Access Device выбираем COM порт нашего адаптера. На вкладке Monitor меняем Baudrate на 38400. И ставим галочку Use K-Line protocol. ОК. Далее. Далее


В появившемя окне пишем имя для нашего профиля, например “XC2768X-136F” и нажимаем Сохранить. ОК.

В итоге видим основное окно программы, начальная настройка завершена, можно подавать питание на ЭБУ и нажимать кнопку Connect.
Если всё сделали правильно, то статус должен смениться на “Ready to Memtool Command“, в противном случае могут быть следующие варианты ошибок:
- “Port error: Не удается найти указанный файл.” – не подключен адаптер или не правильно выбран порт в настройках профиля
- “Start monitor failed” – просто нажать Retry, или переткнуть адаптер и попробовать ещё раз
- “K-Line protocol failed” – возможно забыли подключить 12В питание к адаптеру на пин 16.
- “Bootstrap loader not responding !” – контроллер не отвечает, проверить ещё раз подключение, передёрнуть зажигание (A5)
После успешного подключения первым делом выполняем резервную копию текущей прошивки блока. Для этого в левой части окна нажимаем Read -> New

Задаём блок для считывания с адреса 00C00000, по адрес 00D0FFFF. Итоговый размер получается примерно 1.063M. ОК -> Start

Дожидаемся окончания считывания прошивки и нажимаем Save As. Выбираем надёжное место для хранения оригинальной прошивки
Так же после подключения к блоку и перед записью новой прошивки необходимо настроить защиту для секторов EEPROM, для этого нажимаем SW Protect и отмечаем галочками 16 секторов начиная с 64 (сектора начинающиеся с адресов 0х00С40000 – 0х00С4F000 включительно). Данная настройка записывается в профиль, но всё равно можно на всякий случай проверять, что в правом окне данные сектора отмечены как защищённые от записи.

Полученная от msa96 прошивка представленная в виде бинарного файла (для примера можно взять последнюю версию официальной прошивки: I765XM57), а Infineon MemTool желает видеть файл в HEX формате. Для преобразования воспользуемся утилитой srec_cat. Для тех, кто не умеет пользоваться командной строкой – в архиве есть инструкция. Всё делается одной командой:
srec_cat.exe I765XM57v3.bin -Binary -offset 0x00C00000 -output I765XM57v3.hex -Intel
После выполнения которой, получившийся файл можно загружать в Infineon MemTool, нажав в левой части окна кнопку Open File. Затем Select All и Add Sel

И если уверены, что всё сделали правильно, то можно нажимать кнопку Program. Сначала будет удалена текущая прошивка, затем записана новая, и в конце пройдёт проверка записанных данных



На этапе проверки, в районе отмеченных как защищённые секторов EEPROM (0х00С40000 – 0х00С4F000) счётчик ошибок насчитает их некоторое количество – так и должно быть. Главное, чтобы ошибок не было за пределами данных секторов. Но в любом случае, результат этапа verify будет failed – это нормально. Можно закрывать окно, отключать питание и подключать контроллер обратно к автомобилю.

После прошивки изменения заметны сразу. Машина начала держать холостые обороты в момент начала движения, теперь они не проваливаются с последующим отскоком вверх, и соответственно исчезли все флуктуации. Просто взял и поехал, как на любой нормальной машине, но для меня звучит как чудо. Потому что до этого мой хрей так не умел, особенно в жару, особенно с кондиционером, особенно на 92 бензине. Соответственно и на задней передаче обороты теперь тоже держатся нормально, и на ровном месте теперь заглохнуть не получается. Реакция на педаль газа стала моментальной – когда нажал – тогда и поехал. Такое чувство, что даже включение кондиционера перестало быть заметным, ровно как и пропала куда-то детонация.
Ну и на случай, когда начнёт казаться, что всё не так хорошо, как хотелось бы, и появится подозрение о том, что всё это самовнушение – в прошивке предусмотрен режим включения стоковых настроек, – после включения зажигания нужно нажать и подержать 5 секунд педаль газа в пол, а затем отпустить и завести двигатель. Разница заметна сразу, но так же я заметил, что свежая прошивка I765XM57 отличается от той, что была залита в мой блок с завода (I765XK55) и после этого никем никогда не трогалась. Поэтому если у вас есть подобные описанным в начале проблемы, а официальный дилер разводит руками и отказываться обновлять ПО ЭБУ под предлогом того, что для вашей машины обновлений не поступало – то можно для начала залить свежую версию серийной прошивки, без всяких модификаций – возможно этого будет достаточно.
Результат однозначно радует и остался лишь один вопрос – как я ездил до этого, и зачем так долго надеялся на решение проблем от официального дилера автоваза?
Example verification
test1.bin
#Write in the bin file
-n test1.bin
srec_cat test1.bin -binary -offset -o test1.srec -address-length -line-length
Crop and Generating a Hex Dump
One thing I’m using often is to do a memory dump of my s-record. I can do this with the -hex-dump option:
srec_cat -crop -Output - -hex-dump
💡 After the -Output option there is usually a file name. Using ‘-‘ as file name will write the output to the console.
srec_cat FRDM-KL25Z_CRC.srec -crop 0x500 0x530 -Output - -hex-dump
00000500: BD 46 80 BD B0 B5 82 B0 00 AF 78 60 39 60 10 4C #=F.=05.0./x`9`.L
00000510: 00 25 15 E0 23 1C 1B 02 9A B2 23 0A 9B B2 19 1C #.%.`#....2#..2..
00000520: 7B 68 58 1C 78 60 1B 78 5B B2 59 40 FF 23 19 40 #{hX.x`.x[2Y@.#.@I use that approach to quickly inspect or dump content of my image (.elf/.s19) file. Additionally, this allows me to inspect the memory of the target and compare it with what I have in my file.
💡 The -crop command crops (or cuts) everything out of the data except the range specified (the end address not included).
File type
When input files and output file files, the file type must
test.hex -intel
test.bin -binary
4 Learn from one another
By analogy, if there are multiple App files, one firmware can be merged separately in this way. In addition, in actual projects, internal flash free sectors are often used to save some device parameter information, such as calibration coefficients, device addresses, serial numbers, and other information. We can save the parameter information as a bin file and merge it with the firmware in this way. In this way, the parameters and firmware are written together during mass production to improve production efficiency!
2 Traditional way
Some traditional methods are “earthly methods”, nothing wrong, but more cumbersome. Project types increase, or when the version is released frequently, it becomes more cumbersome and error-prone. A slight operation error may lead to incomplete firmware; burn incomplete firmware, and the machine becomes a “brick”.
- Burn twice, burn BootLoader and App firmware respectively
- After burning the firmware to the chip, read the firmware from the chip and save it as a hex file
- Manually copy and merge firmware
- BootLoader supports App firmware transfer function, only burn the BootLoader, and then upgrade the App later
Outline
Because the GNU (e.g. GNU ARM Embedded/launchpad) toolchain does not include a CRC checksum calculation function, I’m showing how the SRecord utility can be used for this. The SRecord tool is an open source project on SourceForge (http://srecord.sourceforge.net/). It is a command line utility which runs on many platforms. I’m using it in this post with Eclipse (e.g. Freescale Kinetis Design Studio, or any other Eclipse based toolchain using the GNU ARM Embedded (Liviu) with GNU for ARM (GNU for ARM Embedded (Launchpad): https://launchpad.net/gcc-arm-embedded). It goes through the steps to create a checksum, add it to the binary image and checking that checksum in the application.
💡 As the name ‘SRecord’ suggests it deals with S-Records (or S19) files. This is just the default format. SRecord can read and generate pretty much any file format which is used for programming memory devices or microcontroller.
Generating CRC
-CRC16_Big_Endian 0x1FFFE -CCITT
-CRC16_Big_Endian or -crc16-b-e is used to store the CRC is stored in Big Endian format.
Srec_cmp
srec_cmp is a program which can compare two files. Unlike a normal diff, it compares two ‘memory’ files. For example
srec_cmp app1.srec app2.srec
srec_cmp: files "app1.srec" and "app2.srec" differ
See http://srecord.sourceforge.net/man/man1/srec_cmp.html for further information.
Instruction format
srec_cat bin_file_name binary offset offset o srec_file_name addresslengthaddress_len linelengthline_len
- srec_cat: Instruction
- bin_file_name: BIN file name to be converted, that is, input file,Note that the path of the script;
- binary: Instructions are written in binary files,*Parameters to be used;
- offset: Disposal amount, you must connect specific data later;
- o: Express the output;
- srec_file_name: Output file, follow it-o After the parameter;
- address-length: The byte length of the address, such as 0x00001010, if the address is 0x00001010, ifaddress-length=2The address is expressed as1010,ifaddress-length=3The address is expressed as001010;
- line-length: Means the longest number of characters per line, andaddress-lengthSimilar usage,Note that it is meaningless to binary file formatEssence The default value is less than 80 characters, depending on the format. If you need to control the maximum number of bytes of each output record, please use it−Ouput_Block_SizeOptions.
File conversion
You can enter the file type conversion through the software.
Such as hex files to bin file:
srec_cat.exe stm32.hex -intel -offset 0x08000000 -o stm32.bin -binary
Start STM32.HEX from 0x08000000 to Bin file.
bin file to hex file:
srec_cat.exe stm32.bin -binary -offset 0x08000000 -o stm32.hex -intel
Start the STM32.BIN offset 0x08000000 to the Hex file.
Srec_cat
srec_cat is the ‘main’ program of the suite. As the name indicates it can concatenate multiples files. But it can do much more:
- Converting files
- Inserting or removing data
- Joining/splitting files
- Moving data
- Fill in patterns or fill the blanks
- Creating data
- Changing data
- and of course creating multiple kinds of checksums 🙂
There are many good examples how to use it here: http://srecord.sourceforge.net/man/man1/srec_examples.html
1 Merging files
- Combine two files:
copy /b <file0> <file1> <merge-file> - Rename the file:
ren <source_file> <dect_file> - Delete Files:
del <file>
Obviously, we use its merge command to merge BootLoader and App files with only one instruction.
Assuming that there are Boot.bin and App.bin files in the current directory, the merged file is named Firmware.bin.
copy /b .\Boot.bin + .\App.bin Firmware.bin
The directory path of Windows is backslash, which is different from Linux.
3 Complete example
- The first step is to create a new txt file in the firmware directory that needs to be generated
- The second step, type the following content (Boot firmware and App firmware can specify the directory)
copy /b .\Boot.bin + .\App.bin Firmware.bin
srec_cat.exe Firmware.bin -Binary -offset 0x8000000 -o Firmware.hex -Intel
del Firmware.bin
- The third step is to rename the txt file as
".bat"Suffix file, which is the file type of Windows executable script - The fourth step, double-click to run the script, you can generate the target file
If any target file fails to be generated, check whether the relevant source file exists and whether the path is correct.
File interception
If the content of the file is needed, you can use the parameter-crop。
srec_cat.exe stm32.hex -intel -crop 0x08000000 0x08003FFF -o stm32_app.hex -intel
A new file STM32_App.hex will be generated by effective data in the 0x0800000000 -0x08003FFF in the STM32.HEX file. If the code end address is 0x0800 1fff, the newly generated file code range is 0x08000000 -08001ffff.
Content filling
String
If you want to fill in the string information at the designated position specified in the file, such as version information
srec_cat.exe -generate 0x08000000 0x08000005 -repeat-string STM32 stm32.hex -intel -exclude 0x08000000 0x08000005 -o stm32_new.hex -intel
Repeat the “STM32” string information within the range of 0x08000000 0x08000005, and merge with STM32.HEX (excluded data within 0x08000000 0x08000005) to generate new file STM32_New.hex
- -Gene on: Data generator parameter, the address range-data source
- -Repeat-String: String parameters, then access string parameters later
- -exclude: Eliminate the filter parameters, excluding data in a certain range
- Repeat: If the length of the string is less than the reserved range, repeat it. For example, change the 0x14 to 0x16, then the data corresponding to the 0x15 and 0x16 addresses
number
If you want to fill in digital information at the position specified by the file, such as the size of the file
srec_cat.exe -generate 0x08 0x0C -constant-l-e 0x123456 4 stm32.bin -Binary -exclude 0x08 0x0C -o stm32_new.bin -Binary
In the range of 0x08 ~ 0x0c, fill in the hexadecimal number 0x123456 in 4 bytes, and merge with STM32.BIN (data within 0x08 ~ 0x0c), generate new file STM32_New.bin
- -Constant-L-E: Digital value byte width parameters, that is, value-byte width
- Repeat: If the length of the alignment is less than the reserved range, the filling is repeated. For example, if the 0x0C is changed to 0x0d, the data corresponding to the 0x0d address is 0x56 (small end mode)
Generating S-Record Files
Usually the linker main output file is an ELF/Dwarf file which has both code and debug information. The ELF/Dwarf file is used for debugging. All toolchains I’m aware of are able to generate more output files beside of the ELF/Dwarf: S-Record (S19), Intel Hex, etc files. For example in Kinetis Design Studio use the ‘Create flash image’ option in the project settings and press ‘Apply’:
<img aria-describedby="caption-attachment-14795" data-attachment-id="14795" data-permalink="https://mcuoneclipse.com/2015/04/26/crc-checksum-generation-with-srecord-tools-for-gnu-and-eclipse/create-flash-image-2/" data-orig-file="https://mcuoneclipse.files.wordpress.com/2015/04/create-flash-image.png" data-orig-size="583,515" data-comments-opened="1" data-image-meta="{"aperture":"0","credit":"","camera":"","caption":"","created_timestamp":"0","copyright":"","focal_length":"0","iso":"0","shutter_speed":"0","title":"","orientation":"0"}" data-image-title="Create Flash Image" data-image-description="
Create Flash Image
” data-image-caption=”
Create Flash Image
” data-medium-file=”https://mcuoneclipse.files.wordpress.com/2015/04/create-flash-image.png?w=300″ data-large-file=”https://mcuoneclipse.files.wordpress.com/2015/04/create-flash-image.png?w=583″ src=”https://mcuoneclipse.files.wordpress.com/2015/04/create-flash-image.png?w=584″ alt=”Create Flash Image” srcset=”https://mcuoneclipse.files.wordpress.com/2015/04/create-flash-image.png 583w, https://mcuoneclipse.files.wordpress.com/2015/04/create-flash-image.png?w=150 150w, https://mcuoneclipse.files.wordpress.com/2015/04/create-flash-image.png?w=300 300w” sizes=”(max-width: 584px) 100vw, 584px”>
Create Flash Image
Then you can select the ‘Motorola S-record’ option in the project settings:
<img aria-describedby="caption-attachment-14796" data-attachment-id="14796" data-permalink="https://mcuoneclipse.com/2015/04/26/crc-checksum-generation-with-srecord-tools-for-gnu-and-eclipse/motorola-s-record-option/" data-orig-file="https://mcuoneclipse.files.wordpress.com/2015/04/motorola-s-record-option.png" data-orig-size="583,564" data-comments-opened="1" data-image-meta="{"aperture":"0","credit":"","camera":"","caption":"","created_timestamp":"0","copyright":"","focal_length":"0","iso":"0","shutter_speed":"0","title":"","orientation":"0"}" data-image-title="Motorola-s Record Option" data-image-description="
Motorola-s Record Option
” data-image-caption=”
Motorola-s Record Option
” data-medium-file=”https://mcuoneclipse.files.wordpress.com/2015/04/motorola-s-record-option.png?w=300″ data-large-file=”https://mcuoneclipse.files.wordpress.com/2015/04/motorola-s-record-option.png?w=583″ src=”https://mcuoneclipse.files.wordpress.com/2015/04/motorola-s-record-option.png?w=584″ alt=”Motorola-s Record Option” srcset=”https://mcuoneclipse.files.wordpress.com/2015/04/motorola-s-record-option.png 583w, https://mcuoneclipse.files.wordpress.com/2015/04/motorola-s-record-option.png?w=150 150w, https://mcuoneclipse.files.wordpress.com/2015/04/motorola-s-record-option.png?w=300 300w” sizes=”(max-width: 584px) 100vw, 584px”>
Motorola-s Record Option
The generated S19 file can be found in the Debug output folder:
<img aria-describedby="caption-attachment-14797" data-attachment-id="14797" data-permalink="https://mcuoneclipse.com/2015/04/26/crc-checksum-generation-with-srecord-tools-for-gnu-and-eclipse/s19-file/" data-orig-file="https://mcuoneclipse.files.wordpress.com/2015/04/s19-file.png" data-orig-size="254,256" data-comments-opened="1" data-image-meta="{"aperture":"0","credit":"","camera":"","caption":"","created_timestamp":"0","copyright":"","focal_length":"0","iso":"0","shutter_speed":"0","title":"","orientation":"0"}" data-image-title="S19 File" data-image-description="
S19 File
” data-image-caption=”
S19 File
” data-medium-file=”https://mcuoneclipse.files.wordpress.com/2015/04/s19-file.png?w=254″ data-large-file=”https://mcuoneclipse.files.wordpress.com/2015/04/s19-file.png?w=254″ src=”https://mcuoneclipse.files.wordpress.com/2015/04/s19-file.png?w=584″ alt=”S19 File” srcset=”https://mcuoneclipse.files.wordpress.com/2015/04/s19-file.png 254w, https://mcuoneclipse.files.wordpress.com/2015/04/s19-file.png?w=150 150w” sizes=”(max-width: 254px) 100vw, 254px”>
2 Bin to hex
We know that binary (bin) files do not have address information, and the CPU power-on execution does not necessarily start executing code from address 0. For example, the starting execution address of the STM32 chip is 0x8000000. Therefore, it is not possible to burn the bin file through the serial tool, but only through J-link or ST-link, and specify the storage start address before burning. Therefore, it is necessary to convert bin files to hex files.
Bin to hex mode:
- Use the jflash tool to open the combined bin file with jflash and save it as a hex format file
- Burn the bin file to the chip, read it out, and save it as a hex file
- Write a bin to hex tool by yourself
- Use a third-party bin to hex tool
The first two are too cumbersome and inefficient; the third is more flexible, but it takes time; if you use excellent ready-made tools, it is the quickest way. It is recommended to use the “srec_cat.exe” tool, which can be used with Windows scripts.
3.2.1 srec_cat tool
Srec_cat is a very powerful file merging and conversion tool with many support functions, including:
- File merge
- File split
- bin to hex
- hex to bin
- Data fill
- CRC check
In addition, there are a series of srec tools, file comparison tool srec_cmp.exe and file information viewing tool srec_info.exe, which can be downloaded and used from the official website behind the article.
Command format:srec_cat.exe <source file 0> <file type> <source file 1> <file type> <target file> <file type>
srec_cat.exe source0.bin -Binary source1.bin -Binary -o merge.bin -Binary
srec_cat.exe source0.hex -Intel source1.hex -Intel -o merge.hex -Intel
If the files produced by BootLoader and App are in hex format, you can directly use this command to merge them into a hex file, pay attention to the continuity of addresses.
bin to hex
Command format:srec_cat.exe <bin source file> <-Binary> <-offset> <offset address> <-Output> <hex target file> <-Intel>
Convert the Firmware.bin merged with Boot.bin and App.bin into a hex format file.
srec_cat.exe Firmware.bin -Binary -offset 0x8000000 -o Firmware.hex -Intel
- 0x8000000 is the starting execution address of STM32
Installation
SRecord comes with three utilities:
- srec_info: used to retrieve basic information about the file. It reports things like start address.
- srec_cmp: used to compare two files. This utility only tells you if two files are (memory-wise) different or not, but not more.
- srec_cat: This tool is used to extract/add/create/merge/etc files.
All the three tools are command line tools and have extensive support for options. So they easily can be used with make files, scripts or from IDEs as Eclipse. See http://srecord.sourceforge.net/man/index.html for the online manual.
💡 The cool part is that they support ‘input generators’ and ‘filters’, see http://srecord.sourceforge.net/man/man1/srec_input.html
CRC16 Source Files
http://www.menie.org/georges/embedded/crc16.html is a great source for a CRC16 calculation function. Another even better one is on http://www.sunshine2k.de/coding/javascript/crc/crc_js.html. I have updated the source to match the 0x1D0F starting point which is used for -CRC16_Big_Endian. I changed the implementation to use a defined starting point: The interface file:
/* * Copyright 2001-2010 Georges Menie (www.menie.org) * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of California, Berkeley nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _CRC16_H_ #define _CRC16_H_ #define CRC16_START_VAL 0x1D0F /* start value which is used by SRecord tool for -CRC16_Big_Endian */ unsigned short crc16_ccitt(const void *buf, int len, unsigned short start); #endif /* _CRC16_H_ */The implementation file:
/* * Copyright 2001-2010 Georges Menie (www.menie.org) * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of California, Berkeley nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "crc16.h" /* CRC16 implementation according to CCITT standards */ static const unsigned short crc16tab[256]= { 0x0000,0x1021,0x2042,0x3063,0x4084,0x50a5,0x60c6,0x70e7, 0x8108,0x9129,0xa14a,0xb16b,0xc18c,0xd1ad,0xe1ce,0xf1ef, 0x1231,0x0210,0x3273,0x2252,0x52b5,0x4294,0x72f7,0x62d6, 0x9339,0x8318,0xb37b,0xa35a,0xd3bd,0xc39c,0xf3ff,0xe3de, 0x2462,0x3443,0x0420,0x1401,0x64e6,0x74c7,0x44a4,0x5485, 0xa56a,0xb54b,0x8528,0x9509,0xe5ee,0xf5cf,0xc5ac,0xd58d, 0x3653,0x2672,0x1611,0x0630,0x76d7,0x66f6,0x5695,0x46b4, 0xb75b,0xa77a,0x9719,0x8738,0xf7df,0xe7fe,0xd79d,0xc7bc, 0x48c4,0x58e5,0x6886,0x78a7,0x0840,0x1861,0x2802,0x3823, 0xc9cc,0xd9ed,0xe98e,0xf9af,0x8948,0x9969,0xa90a,0xb92b, 0x5af5,0x4ad4,0x7ab7,0x6a96,0x1a71,0x0a50,0x3a33,0x2a12, 0xdbfd,0xcbdc,0xfbbf,0xeb9e,0x9b79,0x8b58,0xbb3b,0xab1a, 0x6ca6,0x7c87,0x4ce4,0x5cc5,0x2c22,0x3c03,0x0c60,0x1c41, 0xedae,0xfd8f,0xcdec,0xddcd,0xad2a,0xbd0b,0x8d68,0x9d49, 0x7e97,0x6eb6,0x5ed5,0x4ef4,0x3e13,0x2e32,0x1e51,0x0e70, 0xff9f,0xefbe,0xdfdd,0xcffc,0xbf1b,0xaf3a,0x9f59,0x8f78, 0x9188,0x81a9,0xb1ca,0xa1eb,0xd10c,0xc12d,0xf14e,0xe16f, 0x1080,0x00a1,0x30c2,0x20e3,0x5004,0x4025,0x7046,0x6067, 0x83b9,0x9398,0xa3fb,0xb3da,0xc33d,0xd31c,0xe37f,0xf35e, 0x02b1,0x1290,0x22f3,0x32d2,0x4235,0x5214,0x6277,0x7256, 0xb5ea,0xa5cb,0x95a8,0x8589,0xf56e,0xe54f,0xd52c,0xc50d, 0x34e2,0x24c3,0x14a0,0x0481,0x7466,0x6447,0x5424,0x4405, 0xa7db,0xb7fa,0x8799,0x97b8,0xe75f,0xf77e,0xc71d,0xd73c, 0x26d3,0x36f2,0x0691,0x16b0,0x6657,0x7676,0x4615,0x5634, 0xd94c,0xc96d,0xf90e,0xe92f,0x99c8,0x89e9,0xb98a,0xa9ab, 0x5844,0x4865,0x7806,0x6827,0x18c0,0x08e1,0x3882,0x28a3, 0xcb7d,0xdb5c,0xeb3f,0xfb1e,0x8bf9,0x9bd8,0xabbb,0xbb9a, 0x4a75,0x5a54,0x6a37,0x7a16,0x0af1,0x1ad0,0x2ab3,0x3a92, 0xfd2e,0xed0f,0xdd6c,0xcd4d,0xbdaa,0xad8b,0x9de8,0x8dc9, 0x7c26,0x6c07,0x5c64,0x4c45,0x3ca2,0x2c83,0x1ce0,0x0cc1, 0xef1f,0xff3e,0xcf5d,0xdf7c,0xaf9b,0xbfba,0x8fd9,0x9ff8, 0x6e17,0x7e36,0x4e55,0x5e74,0x2e93,0x3eb2,0x0ed1,0x1ef0 }; unsigned short crc16_ccitt(const void *buf, int len, unsigned short start) { register int counter; register unsigned short crc = start; for( counter = 0; counter < len; counter++) { crc = (crc<<8) ^ crc16tab[((crc>>8) ^ *(char *)buf++)&0x00FF]; } return crc; }Checking CRC in the Application
Below is a piece of code in the application which checks the CRC:
/* * Application.c * * Created on: 16.04.2015 * Author: Erich Styger */ #include "Application.h" #include "crc16.h" #define CRC_RANGE_START_ADDR 0x00410 /* start addr */ #define CRC_RANGE_END_ADDR 0x1FFFE /* end addr, this one will not be counted */ #define CRC_VALUE_ADDR 0x1FFFE /* address of CRC (16bits) */ void APP_CheckCRC(void) { unsigned short crc; crc = crc16_ccitt((void*)CRC_RANGE_START_ADDR, CRC_RANGE_END_ADDR-CRC_RANGE_START_ADDR, CRC16_START_VAL); if (crc!=*((unsigned short*)CRC_VALUE_ADDR)) { for(;;) {} /* error! CRC does not match! */ } }The above code assumes that the 16bit CRC is stored at address 0x1FFFE. The application checks the CRC for the code space from address 0x410 up to 0x1FFFD (which does *not* include the CRC itself which is at 0x1FFFE-0x1FFFF).
Using Command Files
Instead passing everything on the command line, I can call the SRecord tool suite programs with the options in an external file. The syntax is
<SrecordProgram> @filenamesrec_cat @crc_cmd.txtDumping the CRC for a memory range
# srec_cat command file to dump the CRC for a code area # Usage: srec_cat @filename FRDM-KL25Z_CRC.srec # input file -fill 0xFF 0x0410 0x20000 # fill code area with 0xff -crop 0x0410 0x1FFFE # just keep code area for CRC calculation below (CRC will be at 0x1FFFE..0x1FFFF) -CRC16_Big_Endian 0x1FFFE -CCITT # calculate big endian CCITT CRC16 at given address. -crop 0x1FFFE 0x20000 # keep the CRC itself -Output # produce output - # '-' is special 'file': use console output -hex-dump # dump in hex formatThat way I can have things commented (comments start with ‘#’) and keep things readable. The above program calculates the CRC over a given range, stores the value at the artificial address 0x20000 (outside of the code area) and dumps the 16bit value on the console:
<img loading="lazy" aria-describedby="caption-attachment-14869" data-attachment-id="14869" data-permalink="https://mcuoneclipse.com/2015/04/26/crc-checksum-generation-with-srecord-tools-for-gnu-and-eclipse/executing-script-to-dump-crc-value-2/" data-orig-file="https://mcuoneclipse.files.wordpress.com/2015/04/executing-script-to-dump-crc-value2.png" data-orig-size="677,102" data-comments-opened="1" data-image-meta="{"aperture":"0","credit":"","camera":"","caption":"","created_timestamp":"0","copyright":"","focal_length":"0","iso":"0","shutter_speed":"0","title":"","orientation":"0"}" data-image-title="executing script to dump CRC value" data-image-description="
executing script to dump CRC value
" data-image-caption="
executing script to dump CRC value
" data-medium-file="https://mcuoneclipse.files.wordpress.com/2015/04/executing-script-to-dump-crc-value2.png?w=300" data-large-file="https://mcuoneclipse.files.wordpress.com/2015/04/executing-script-to-dump-crc-value2.png?w=584" src="https://mcuoneclipse.files.wordpress.com/2015/04/executing-script-to-dump-crc-value2.png?w=584&h=88" alt="executing script to dump CRC value" srcset="https://mcuoneclipse.files.wordpress.com/2015/04/executing-script-to-dump-crc-value2.png?w=584&h=88 584w, https://mcuoneclipse.files.wordpress.com/2015/04/executing-script-to-dump-crc-value2.png?w=150&h=23 150w, https://mcuoneclipse.files.wordpress.com/2015/04/executing-script-to-dump-crc-value2.png?w=300&h=45 300w, https://mcuoneclipse.files.wordpress.com/2015/04/executing-script-to-dump-crc-value2.png 677w" sizes="(max-width: 584px) 100vw, 584px">
executing script to dump CRC value
Incorporating the CRC Value into the Application
Knowing the CRC, I need to incorporate the CRC value itself into my application. One way would be to do this in the GNU linker script itself (see “FILLing unused Memory with the GNU Linker“). However, that would be a manual process:
- Determine the CRC value with SRecord and dump it
- Enter the CRC value into the linker script
Another approach would be:
- Generate the CRC with SRecord and produce the S19 file which only has the CRC in it (CRC S19 file)
- Merge the application S19 file with the CRC S19 file
FRDM-KL25Z_CRC.srec # input file -fill 0xFF 0x0410 0x20000 # fill code area with 0xff -crop 0x0410 0x1FFFE # just keep code area for CRC calculation below (CRC will be at 0x1FFFE..0x1FFFF) -CRC16_Big_Endian 0x1FFFE -CCITT # calculate big endian CCITT CRC16 at given address. -crop 0x1FFFE 0x20000 # keep the CRC itself -Output # produce output FRDM-KL25Z_CRC.srec # S19 with CRC onlyWith this, I have only the CRC in FRDM-KL25Z_CRC.srec.
Then I need to fill the unused areas in the application file. Here again, I can generate a ‘filled’ file:
srec_cat FRDM-KL25Z_CRC.srec -fill 0xFF 0x0410 0x1FFFE -Output FRDM-KL25Z_CRC_Filled.srecFinally, concatenate the two files with
srec_cat FRDM-KL25Z_CRC_Filled.srec FRDM-KL25Z_CRC.srec -Output Debug\FRDM-KL25Z_CRC_Added.srecHowever, this involves using temporary files which is not ideal. A better approach is to do everything in one step, with a single command file like this:
# srec_cat command file to add the CRC and produce application file to be flashed # Usage: srec_cat @filename #first: create CRC checksum FRDM-KL25Z_CRC.srec # input file -fill 0xFF 0x0410 0x20000 # fill code area with 0xff -crop 0x0410 0x1FFFE # just keep code area for CRC calculation below (CRC will be at 0x1FFFE..0x1FFFF) -CRC16_Big_Endian 0x1FFFE -CCITT # calculate big endian CCITT CRC16 at given address. -crop 0x1FFFE 0x20000 # keep the CRC itself #second: add application file FRDM-KL25Z_CRC.srec # input file -fill 0xFF 0x0410 0x1FFFE # fill code area with 0xff #finally, produce the output file -Output # produce output FRDM-KL25Z_CRC_Added.srecTo me, this is really a cool thing of the SRecord tool: the ability to line up files and content and then merge it 🙂
And as expected: the application image file has the CRC added:
<img loading="lazy" aria-describedby="caption-attachment-14870" data-attachment-id="14870" data-permalink="https://mcuoneclipse.com/2015/04/26/crc-checksum-generation-with-srecord-tools-for-gnu-and-eclipse/crc-added-to-the-application-image-file/" data-orig-file="https://mcuoneclipse.files.wordpress.com/2015/04/crc-added-to-the-application-image-file.png" data-orig-size="661,270" data-comments-opened="1" data-image-meta="{"aperture":"0","credit":"","camera":"","caption":"","created_timestamp":"0","copyright":"","focal_length":"0","iso":"0","shutter_speed":"0","title":"","orientation":"0"}" data-image-title="CRC Added to the Application Image File" data-image-description="
CRC Added to the Application Image File
" data-image-caption="
CRC Added to the Application Image File
" data-medium-file="https://mcuoneclipse.files.wordpress.com/2015/04/crc-added-to-the-application-image-file.png?w=300" data-large-file="https://mcuoneclipse.files.wordpress.com/2015/04/crc-added-to-the-application-image-file.png?w=584" src="https://mcuoneclipse.files.wordpress.com/2015/04/crc-added-to-the-application-image-file.png?w=584&h=239" alt="CRC Added to the Application Image File" srcset="https://mcuoneclipse.files.wordpress.com/2015/04/crc-added-to-the-application-image-file.png?w=584&h=239 584w, https://mcuoneclipse.files.wordpress.com/2015/04/crc-added-to-the-application-image-file.png?w=150&h=61 150w, https://mcuoneclipse.files.wordpress.com/2015/04/crc-added-to-the-application-image-file.png?w=300&h=123 300w, https://mcuoneclipse.files.wordpress.com/2015/04/crc-added-to-the-application-image-file.png 661w" sizes="(max-width: 584px) 100vw, 584px">
CRC Added to the Application Image File
Adding CRC as Post-Build Step
Now I have the ability to add the CRC to my application file. It would be great if this could be part of my build process? Using normal make files, I simply would call srec_cat after linking. The same thing can be done with Eclipse as ‘Post-Build-Step’. For example to dump the CRC value, I can have this in the project settings:
<img loading="lazy" aria-describedby="caption-attachment-14871" data-attachment-id="14871" data-permalink="https://mcuoneclipse.com/2015/04/26/crc-checksum-generation-with-srecord-tools-for-gnu-and-eclipse/post-build-step-to-dump-crc/" data-orig-file="https://mcuoneclipse.files.wordpress.com/2015/04/post-build-step-to-dump-crc.png" data-orig-size="818,576" data-comments-opened="1" data-image-meta="{"aperture":"0","credit":"","camera":"","caption":"","created_timestamp":"0","copyright":"","focal_length":"0","iso":"0","shutter_speed":"0","title":"","orientation":"0"}" data-image-title="Post Build Step to Dump CRC" data-image-description="
Post Build Step to Dump CRC
" data-image-caption="
Post Build Step to Dump CRC
" data-medium-file="https://mcuoneclipse.files.wordpress.com/2015/04/post-build-step-to-dump-crc.png?w=300" data-large-file="https://mcuoneclipse.files.wordpress.com/2015/04/post-build-step-to-dump-crc.png?w=584" src="https://mcuoneclipse.files.wordpress.com/2015/04/post-build-step-to-dump-crc.png?w=584&h=411" alt="Post Build Step to Dump CRC" srcset="https://mcuoneclipse.files.wordpress.com/2015/04/post-build-step-to-dump-crc.png?w=584&h=411 584w, https://mcuoneclipse.files.wordpress.com/2015/04/post-build-step-to-dump-crc.png?w=150&h=106 150w, https://mcuoneclipse.files.wordpress.com/2015/04/post-build-step-to-dump-crc.png?w=300&h=211 300w, https://mcuoneclipse.files.wordpress.com/2015/04/post-build-step-to-dump-crc.png?w=768&h=541 768w, https://mcuoneclipse.files.wordpress.com/2015/04/post-build-step-to-dump-crc.png 818w" sizes="(max-width: 584px) 100vw, 584px">
Post Build Step to Dump CRC
💡 Keep in mind that the ‘current directory’ for the build process is the output folder, usually the ‘Debug’ folder.
And it will dump the CRC at the end of the build process:
<img loading="lazy" aria-describedby="caption-attachment-14872" data-attachment-id="14872" data-permalink="https://mcuoneclipse.com/2015/04/26/crc-checksum-generation-with-srecord-tools-for-gnu-and-eclipse/srec_cat-as-post-build-step-in-the-eclipse-console-view/" data-orig-file="https://mcuoneclipse.files.wordpress.com/2015/04/srec_cat-as-post-build-step-in-the-eclipse-console-view.png" data-orig-size="929,364" data-comments-opened="1" data-image-meta="{"aperture":"0","credit":"","camera":"","caption":"","created_timestamp":"0","copyright":"","focal_length":"0","iso":"0","shutter_speed":"0","title":"","orientation":"0"}" data-image-title="srec_cat as post-build step in the Eclipse Console View" data-image-description="
srec_cat as post-build step in the Eclipse Console View
" data-image-caption="
srec_cat as post-build step in the Eclipse Console View
" data-medium-file="https://mcuoneclipse.files.wordpress.com/2015/04/srec_cat-as-post-build-step-in-the-eclipse-console-view.png?w=300" data-large-file="https://mcuoneclipse.files.wordpress.com/2015/04/srec_cat-as-post-build-step-in-the-eclipse-console-view.png?w=584" src="https://mcuoneclipse.files.wordpress.com/2015/04/srec_cat-as-post-build-step-in-the-eclipse-console-view.png?w=584&h=229" alt="srec_cat as post-build step in the Eclipse Console View" srcset="https://mcuoneclipse.files.wordpress.com/2015/04/srec_cat-as-post-build-step-in-the-eclipse-console-view.png?w=584&h=229 584w, https://mcuoneclipse.files.wordpress.com/2015/04/srec_cat-as-post-build-step-in-the-eclipse-console-view.png?w=150&h=59 150w, https://mcuoneclipse.files.wordpress.com/2015/04/srec_cat-as-post-build-step-in-the-eclipse-console-view.png?w=300&h=118 300w, https://mcuoneclipse.files.wordpress.com/2015/04/srec_cat-as-post-build-step-in-the-eclipse-console-view.png?w=768&h=301 768w, https://mcuoneclipse.files.wordpress.com/2015/04/srec_cat-as-post-build-step-in-the-eclipse-console-view.png 929w" sizes="(max-width: 584px) 100vw, 584px">
srec_cat as post-build step in the Eclipse Console View
The same way I can add the CRC to the application:
<img loading="lazy" aria-describedby="caption-attachment-14873" data-attachment-id="14873" data-permalink="https://mcuoneclipse.com/2015/04/26/crc-checksum-generation-with-srecord-tools-for-gnu-and-eclipse/adding-crc-to-application/" data-orig-file="https://mcuoneclipse.files.wordpress.com/2015/04/adding-crc-to-application.png" data-orig-size="835,553" data-comments-opened="1" data-image-meta="{"aperture":"0","credit":"","camera":"","caption":"","created_timestamp":"0","copyright":"","focal_length":"0","iso":"0","shutter_speed":"0","title":"","orientation":"0"}" data-image-title="Adding CRC to Application" data-image-description="
Adding CRC to Application
" data-image-caption="
Adding CRC to Application
" data-medium-file="https://mcuoneclipse.files.wordpress.com/2015/04/adding-crc-to-application.png?w=300" data-large-file="https://mcuoneclipse.files.wordpress.com/2015/04/adding-crc-to-application.png?w=584" src="https://mcuoneclipse.files.wordpress.com/2015/04/adding-crc-to-application.png?w=584&h=387" alt="Adding CRC to Application" srcset="https://mcuoneclipse.files.wordpress.com/2015/04/adding-crc-to-application.png?w=584&h=387 584w, https://mcuoneclipse.files.wordpress.com/2015/04/adding-crc-to-application.png?w=150&h=99 150w, https://mcuoneclipse.files.wordpress.com/2015/04/adding-crc-to-application.png?w=300&h=199 300w, https://mcuoneclipse.files.wordpress.com/2015/04/adding-crc-to-application.png?w=768&h=509 768w, https://mcuoneclipse.files.wordpress.com/2015/04/adding-crc-to-application.png 835w" sizes="(max-width: 584px) 100vw, 584px">
Adding CRC to Application
However, this will fail for a clean build:
<img loading="lazy" aria-describedby="caption-attachment-14874" data-attachment-id="14874" data-permalink="https://mcuoneclipse.com/2015/04/26/crc-checksum-generation-with-srecord-tools-for-gnu-and-eclipse/error-while-adding-crc/" data-orig-file="https://mcuoneclipse.files.wordpress.com/2015/04/error-while-adding-crc.png" data-orig-size="1063,433" data-comments-opened="1" data-image-meta="{"aperture":"0","credit":"","camera":"","caption":"","created_timestamp":"0","copyright":"","focal_length":"0","iso":"0","shutter_speed":"0","title":"","orientation":"0"}" data-image-title="Error while adding CRC" data-image-description="
Error while adding CRC
" data-image-caption="
Error while adding CRC
" data-medium-file="https://mcuoneclipse.files.wordpress.com/2015/04/error-while-adding-crc.png?w=300" data-large-file="https://mcuoneclipse.files.wordpress.com/2015/04/error-while-adding-crc.png?w=584" src="https://mcuoneclipse.files.wordpress.com/2015/04/error-while-adding-crc.png?w=584&h=238" alt="Error while adding CRC" srcset="https://mcuoneclipse.files.wordpress.com/2015/04/error-while-adding-crc.png?w=584&h=238 584w, https://mcuoneclipse.files.wordpress.com/2015/04/error-while-adding-crc.png?w=150&h=61 150w, https://mcuoneclipse.files.wordpress.com/2015/04/error-while-adding-crc.png?w=300&h=122 300w, https://mcuoneclipse.files.wordpress.com/2015/04/error-while-adding-crc.png?w=768&h=313 768w, https://mcuoneclipse.files.wordpress.com/2015/04/error-while-adding-crc.png?w=1024&h=417 1024w, https://mcuoneclipse.files.wordpress.com/2015/04/error-while-adding-crc.png 1063w" sizes="(max-width: 584px) 100vw, 584px">
Error while adding CRC
💡 One strange thing I noticed: as soon as I had multiple commands, I had to use ‘/’ instead of ‘\’ on Windows.
<img loading="lazy" aria-describedby="caption-attachment-14875" data-attachment-id="14875" data-permalink="https://mcuoneclipse.com/2015/04/26/crc-checksum-generation-with-srecord-tools-for-gnu-and-eclipse/generating-s19-and-crc/" data-orig-file="https://mcuoneclipse.files.wordpress.com/2015/04/generating-s19-and-crc.png" data-orig-size="927,441" data-comments-opened="1" data-image-meta="{"aperture":"0","credit":"","camera":"","caption":"","created_timestamp":"0","copyright":"","focal_length":"0","iso":"0","shutter_speed":"0","title":"","orientation":"0"}" data-image-title="Generating S19 and CRC" data-image-description="
Generating S19 and CRC
" data-image-caption="
Generating S19 and CRC
" data-medium-file="https://mcuoneclipse.files.wordpress.com/2015/04/generating-s19-and-crc.png?w=300" data-large-file="https://mcuoneclipse.files.wordpress.com/2015/04/generating-s19-and-crc.png?w=584" src="https://mcuoneclipse.files.wordpress.com/2015/04/generating-s19-and-crc.png?w=584&h=278" alt="Generating S19 and CRC" srcset="https://mcuoneclipse.files.wordpress.com/2015/04/generating-s19-and-crc.png?w=584&h=278 584w, https://mcuoneclipse.files.wordpress.com/2015/04/generating-s19-and-crc.png?w=150&h=71 150w, https://mcuoneclipse.files.wordpress.com/2015/04/generating-s19-and-crc.png?w=300&h=143 300w, https://mcuoneclipse.files.wordpress.com/2015/04/generating-s19-and-crc.png?w=768&h=365 768w, https://mcuoneclipse.files.wordpress.com/2015/04/generating-s19-and-crc.png 927w" sizes="(max-width: 584px) 100vw, 584px">
Generating S19 and CRC
With this, everything works as expected:
<img loading="lazy" aria-describedby="caption-attachment-14876" data-attachment-id="14876" data-permalink="https://mcuoneclipse.com/2015/04/26/crc-checksum-generation-with-srecord-tools-for-gnu-and-eclipse/console-output-generating-s19-file-and-adding-crc/" data-orig-file="https://mcuoneclipse.files.wordpress.com/2015/04/console-output-generating-s19-file-and-adding-crc.png" data-orig-size="1033,326" data-comments-opened="1" data-image-meta="{"aperture":"0","credit":"","camera":"","caption":"","created_timestamp":"0","copyright":"","focal_length":"0","iso":"0","shutter_speed":"0","title":"","orientation":"0"}" data-image-title="Console Output generating S19 file and adding CRC" data-image-description="
Console Output generating S19 file and adding CRC
" data-image-caption="
Console Output generating S19 file and adding CRC
" data-medium-file="https://mcuoneclipse.files.wordpress.com/2015/04/console-output-generating-s19-file-and-adding-crc.png?w=300" data-large-file="https://mcuoneclipse.files.wordpress.com/2015/04/console-output-generating-s19-file-and-adding-crc.png?w=584" src="https://mcuoneclipse.files.wordpress.com/2015/04/console-output-generating-s19-file-and-adding-crc.png?w=584&h=184" alt="Console Output generating S19 file and adding CRC" srcset="https://mcuoneclipse.files.wordpress.com/2015/04/console-output-generating-s19-file-and-adding-crc.png?w=584&h=184 584w, https://mcuoneclipse.files.wordpress.com/2015/04/console-output-generating-s19-file-and-adding-crc.png?w=150&h=47 150w, https://mcuoneclipse.files.wordpress.com/2015/04/console-output-generating-s19-file-and-adding-crc.png?w=300&h=95 300w, https://mcuoneclipse.files.wordpress.com/2015/04/console-output-generating-s19-file-and-adding-crc.png?w=768&h=242 768w, https://mcuoneclipse.files.wordpress.com/2015/04/console-output-generating-s19-file-and-adding-crc.png?w=1024&h=323 1024w, https://mcuoneclipse.files.wordpress.com/2015/04/console-output-generating-s19-file-and-adding-crc.png 1033w" sizes="(max-width: 584px) 100vw, 584px">
Console Output generating S19 file and adding CRC
Summary
Generating a CRC is not possible directly with the GNU linker. But this is not a problem, as there is an even more powerful way with the ‘SRecord’ utilities: with the SRecord utilities I can almost any manipulation of the output files I need, plus best of all: it is open source too 🙂
I have put my project used in this post on GitHub here: https://github.com/ErichStyger/mcuoneclipse/tree/master/Examples/KDS/FRDM-KL25Z/FRDM-KL25Z_CRC
Links
- ‘SRecord’ home page: http://srecord.sourceforge.net/
- ‘SRecord’ examples: http://srecord.sourceforge.net/man/man1/srec_examples.html
- Online CRC calculation: http://www.lammertbies.nl/comm/info/crc-calculation.html
- GNU ARM Eclipse Plugins
- GNU for ARM Embedded (Launchpad): https://launchpad.net/gcc-arm-embedded
- Generating S19 Files with CodeWarrior: https://mcuoneclipse.com/2012/09/13/s-record-generation-with-gcc-for-armkinetis/
- Generating S19 Files with Kinetis Design Studio: https://mcuoneclipse.com/2014/04/20/binary-files-for-the-mbed-bootloader-with-eclipse-and-gnu-arm-eclipse-plugins/
- CRC16 CCITT Example source code: http://www.menie.org/georges/embedded/crc16.html
- Post-Build-Steps in Eclipse: Executing Multiple Commands as Post-Build Steps in Eclipse
Srec_info
srec_info gives basic information about the file:
srec_info Debug\FRDM-KL25Z_CRC.srec
Format: Motorola S-Record Header: "FRDM-KL25Z_CRC.srec" Execution Start Address: 000007CD Data: 0000 - 00BF 0400 - 0C3B
See http://srecord.sourceforge.net/man/man1/srec_info.html for further information
Filling Memory
Typically a data file as the Motorola S19/SRecord only describes the bytes to be programmed, but not the ‘holes’ or gaps in the memory map. If building a CRC over a memory area with gaps, I need to define it first. For this I can use the -fill command:
-fill [ ]
To fill multiple areas, e.g. to fill 0x100-0x1FF and 0x300-0x3FF with 0xFF, I could use
-fill 0xFF 0x100 0x200 -fill 0xFF 0x300 0x400
-fill 0xFF 0x100 0x200 0x300 0x400
MEMORY {
m_interrupts (RX) : ORIGIN = 0x00000000, LENGTH = 0x000000C0
m_text (RX) : ORIGIN = 0x00000410, LENGTH = 0x0001FBF0
m_data (RW) : ORIGIN = 0x1FFFF000, LENGTH = 0x00004000
m_cfmprotrom (RX) : ORIGIN = 0x00000400, LENGTH = 0x00000010
}To fill the interrupt table (m_interrupts) and the code (m_text) with 0xFF and dump it, I can use
-fill 0xFF 0x0000 0x00C0 0x0410 0x20000
3 Efficient way
Our goal is to generate a release firmware through automated script merging to improve efficiency and ensure the integrity of the firmware.
Use environment
In the Linux environment, sometimes you need to convert the bin file into a SREC file, so you can use the SRE_CAT instruction in the shell script.
Foreword
The use of the image file tool SREC_CAT, how to achieve the functions you need through related parameters.
Download link:SRecord
References
Reprinted! Intersection Intersection









