|
| 1 | +#!/bin/bash |
| 2 | +# https://gist.github.com/PonomarevDA/829961851abeca5c51154a0882a625fa |
| 3 | +# This software is distributed under the terms of the MIT License. |
| 4 | +# Copyright (c) 2023-2026 Dmitry Ponomarev. |
| 5 | +# Author: Dmitry Ponomarev <ponomarevda96@gmail.com> |
| 6 | + |
| 7 | +SCRIPT_NAME="flash.sh" |
| 8 | +VERSION="v1.1.0" |
| 9 | + |
| 10 | +BINARY_FILE=$1 |
| 11 | + |
| 12 | +RED='\033[0;31m' |
| 13 | +NC='\033[0m' |
| 14 | +if [ -z "$BINARY_FILE" ]; then |
| 15 | + echo -e "${RED}${SCRIPT_NAME} ${VERSION} error on line $LINENO: expected an argument!${NC}" |
| 16 | + exit |
| 17 | +elif [ ! -f "$BINARY_FILE" ]; then |
| 18 | + echo -e "${RED}${SCRIPT_NAME} ${VERSION} error on line $LINENO: specified file $BINARY_FILE is not exist!${NC}" |
| 19 | + exit |
| 20 | +elif [[ ! $BINARY_FILE == *.bin ]]; then |
| 21 | + echo -e "${RED}${SCRIPT_NAME} ${VERSION} error on line $LINENO: speficied file must have .bin extension!${NC}" |
| 22 | + exit |
| 23 | +fi |
| 24 | + |
| 25 | +for attempt in {1..25}; do |
| 26 | + echo "" |
| 27 | + echo "${SCRIPT_NAME} ${VERSION}: attempt $attempt. Trying to load the firmware..." |
| 28 | + echo -en "\007" |
| 29 | + |
| 30 | + output=$(st-info --probe) |
| 31 | + |
| 32 | + is_programmer_not_found=$(echo "$output" | grep "Found 0 stlink programmers") |
| 33 | + if [ ! -z "$is_programmer_not_found" ]; then |
| 34 | + echo "${SCRIPT_NAME} ${VERSION}: stlink programmer not found. Please connect it to your USB port!" |
| 35 | + sleep 2 |
| 36 | + continue |
| 37 | + fi |
| 38 | + |
| 39 | + is_device_not_found=$(echo "$output" | grep "unknown device") |
| 40 | + if [ ! -z "$is_device_not_found" ]; then |
| 41 | + echo "${SCRIPT_NAME} ${VERSION}: STM32 not found. Please connect it to the stlink programmer!" |
| 42 | + sleep 2 |
| 43 | + continue |
| 44 | + fi |
| 45 | + |
| 46 | + # stm32f103 has a wrong flash size. It says 64 KBytes, but it is actually 128 KBytes! |
| 47 | + # Medium-density for old versions of st-link, MD for the newer versions of st-link |
| 48 | + is_stm32f103=$(echo "$output" | grep "F1xx Medium-density\|STM32F1xx_MD") |
| 49 | + if [ ! -z "$is_stm32f103" ]; then |
| 50 | + EXPLICIT_FLASH_SIZE="--flash=0x00020000" |
| 51 | + fi |
| 52 | + |
| 53 | + output=$(st-flash $EXPLICIT_FLASH_SIZE --connect-under-reset --reset write $BINARY_FILE 0x8000000 | tee /dev/tty) |
| 54 | + compare_res=$(echo "$output" | grep "pages written") |
| 55 | + if [ -z "$compare_res" ]; then |
| 56 | + sleep 2 |
| 57 | + else |
| 58 | + echo "${SCRIPT_NAME} ${VERSION}: done" |
| 59 | + for attempt in {1..15}; do |
| 60 | + sleep 0.1 |
| 61 | + echo -en "\007" |
| 62 | + done |
| 63 | + exit |
| 64 | + fi |
| 65 | +done |
| 66 | + |
| 67 | +for attempt in {1..15}; do |
| 68 | + sleep 0.1 |
| 69 | + echo -en "\007" |
| 70 | +done |
0 commit comments