diff --git a/examples/stm32/nucleo-f746zg-freertos-tcp/FreeRTOSConfig.h b/examples/stm32/nucleo-f746zg-freertos-tcp/FreeRTOSConfig.h new file mode 100644 index 00000000..75960f44 --- /dev/null +++ b/examples/stm32/nucleo-f746zg-freertos-tcp/FreeRTOSConfig.h @@ -0,0 +1,39 @@ +#pragma once + +#include "hal.h" + +#define configUSE_PREEMPTION 1 +#define configCPU_CLOCK_HZ SYS_FREQUENCY +#define configTICK_RATE_HZ 1000 +#define configMAX_PRIORITIES 5 +#define configUSE_16_BIT_TICKS 0 +#define configUSE_TICK_HOOK 0 +#define configUSE_IDLE_HOOK 0 +#define configUSE_TIMERS 0 +#define configUSE_CO_ROUTINES 0 +#define configUSE_MALLOC_FAILED_HOOK 0 +#define configUSE_COUNTING_SEMAPHORES 1 +#define configMINIMAL_STACK_SIZE 128 +#define configTOTAL_HEAP_SIZE (1024 * 128) +#define INCLUDE_vTaskDelay 1 +#define INCLUDE_xTaskGetSchedulerState 1 + +#ifdef __NVIC_PRIO_BITS +#define configPRIO_BITS __NVIC_PRIO_BITS +#else +#define configPRIO_BITS 4 +#endif +#define configLIBRARY_LOWEST_INTERRUPT_PRIORITY 15 +#define configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY 5 +#define configKERNEL_INTERRUPT_PRIORITY \ + (configLIBRARY_LOWEST_INTERRUPT_PRIORITY << (8 - configPRIO_BITS)) + +#define configMAX_SYSCALL_INTERRUPT_PRIORITY \ + (configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY << (8 - configPRIO_BITS)) + +#define configASSERT(expr) \ + if (!(expr)) printf("FAILURE %s:%d: %s\n", __FILE__, __LINE__, #expr) + +#define vPortSVCHandler SVC_Handler +#define xPortPendSVHandler PendSV_Handler +// We'll call xPortSysTickHandler from SysTick_Handler ourselves diff --git a/examples/stm32/nucleo-f746zg-freertos-tcp/FreeRTOSIPConfig.h b/examples/stm32/nucleo-f746zg-freertos-tcp/FreeRTOSIPConfig.h new file mode 100644 index 00000000..d1adf6f7 --- /dev/null +++ b/examples/stm32/nucleo-f746zg-freertos-tcp/FreeRTOSIPConfig.h @@ -0,0 +1,336 @@ +/* + * FreeRTOS V202212.00 + * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy of + * this software and associated documentation files (the "Software"), to deal in + * the Software without restriction, including without limitation the rights to + * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of + * the Software, and to permit persons to whom the Software is furnished to do so, + * subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS + * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER + * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN + * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + * https://www.FreeRTOS.org + * https://github.com/FreeRTOS + * + */ + + +/***************************************************************************** + * + * See the following URL for configuration information. + * https://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/TCP_IP_Configuration.html + * + *****************************************************************************/ + +#ifndef FREERTOS_IP_CONFIG_H +#define FREERTOS_IP_CONFIG_H + +/* Prototype for the function used to print out. In this case it prints to the +console before the network is connected then a UDP port after the network has +connected. */ +extern void vLoggingPrintf( const char *pcFormatString, ... ); + + +/* Set to 1 to print out debug messages. If ipconfigHAS_DEBUG_PRINTF is set to +1 then FreeRTOS_debug_printf should be defined to the function used to print +out the debugging messages. */ +#define ipconfigHAS_DEBUG_PRINTF 0 + +#ifdef HEAP3 + #define xPortGetMinimumEverFreeHeapSize(x) 0 + #define xPortGetFreeHeapSize() 0 +#endif + +#if( ipconfigHAS_DEBUG_PRINTF == 1 ) +#include + #define FreeRTOS_debug_printf(X) \ + printf("%p->%s %d: ", \ + xTaskGetCurrentTaskHandle(), \ + __FUNCTION__, \ + __LINE__); \ + vLoggingPrintf X +#endif + +/* Set to 1 to print out non debugging messages, for example the output of the +FreeRTOS_netstat() command, and ping replies. If ipconfigHAS_PRINTF is set to 1 +then FreeRTOS_printf should be set to the function used to print out the +messages. */ +#define ipconfigHAS_PRINTF 0 +#if( ipconfigHAS_PRINTF == 1 ) +#include + #define FreeRTOS_printf(X) \ + printf("%p->%s %d: ", \ + xTaskGetCurrentTaskHandle(), \ + __FUNCTION__, \ + __LINE__); \ + vLoggingPrintf X +#endif + +/* Define the byte order of the target MCU (the MCU FreeRTOS+TCP is executing +on). Valid options are pdFREERTOS_BIG_ENDIAN and pdFREERTOS_LITTLE_ENDIAN. */ +#define ipconfigBYTE_ORDER pdFREERTOS_LITTLE_ENDIAN + +/* If the network card/driver includes checksum offloading (IP/TCP/UDP checksums) +then set ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM to 1 to prevent the software +stack repeating the checksum calculations. */ +#define ipconfigDRIVER_INCLUDED_RX_IP_CHECKSUM 1 + +/* Several API's will block until the result is known, or the action has been +performed, for example FreeRTOS_send() and FreeRTOS_recv(). The timeouts can be +set per socket, using setsockopt(). If not set, the times below will be +used as defaults. */ +#define ipconfigSOCK_DEFAULT_RECEIVE_BLOCK_TIME ( 5000 ) +#define ipconfigSOCK_DEFAULT_SEND_BLOCK_TIME ( 5000 ) + +/* Include support for LLMNR: Link-local Multicast Name Resolution +(non-Microsoft) */ +#define ipconfigUSE_LLMNR ( 0 ) + +/* Include support for NBNS: NetBIOS Name Service (Microsoft) */ +#define ipconfigUSE_NBNS ( 0 ) + +/* Include support for DNS caching. For TCP, having a small DNS cache is very +useful. When a cache is present, ipconfigDNS_REQUEST_ATTEMPTS can be kept low +and also DNS may use small timeouts. If a DNS reply comes in after the DNS +socket has been destroyed, the result will be stored into the cache. The next +call to FreeRTOS_gethostbyname() will return immediately, without even creating +a socket. */ +#define ipconfigUSE_DNS_CACHE ( 0 ) +#define ipconfigDNS_CACHE_NAME_LENGTH ( 16 ) +#define ipconfigDNS_CACHE_ENTRIES ( 4 ) +#define ipconfigDNS_REQUEST_ATTEMPTS ( 2 ) + +/* The IP stack executes it its own task (although any application task can make +use of its services through the published sockets API). ipconfigUDP_TASK_PRIORITY +sets the priority of the task that executes the IP stack. The priority is a +standard FreeRTOS task priority so can take any value from 0 (the lowest +priority) to (configMAX_PRIORITIES - 1) (the highest priority). +configMAX_PRIORITIES is a standard FreeRTOS configuration parameter defined in +FreeRTOSConfig.h, not FreeRTOSIPConfig.h. Consideration needs to be given as to +the priority assigned to the task executing the IP stack relative to the +priority assigned to tasks that use the IP stack. */ +#define ipconfigIP_TASK_PRIORITY ( configMAX_PRIORITIES - 2 ) + +/* The size, in words (not bytes), of the stack allocated to the FreeRTOS+TCP +task. This setting is less important when the FreeRTOS Win32 simulator is used +as the Win32 simulator only stores a fixed amount of information on the task +stack. FreeRTOS includes optional stack overflow detection, see: +http://www.freertos.org/Stacks-and-stack-overflow-checking.html */ +#define ipconfigIP_TASK_STACK_SIZE_WORDS ( configMINIMAL_STACK_SIZE * 5 ) + +/* ipconfigRAND32() is called by the IP stack to generate random numbers for +things such as a DHCP transaction number or initial sequence number. Random +number generation is performed via this macro to allow applications to use their +own random number generation method. For example, it might be possible to +generate a random number by sampling noise on an analogue input. */ +extern UBaseType_t uxRand(); +#define ipconfigRAND32() uxRand() + +/* If ipconfigUSE_NETWORK_EVENT_HOOK is set to 1 then FreeRTOS+TCP will call the +network event hook at the appropriate times. If ipconfigUSE_NETWORK_EVENT_HOOK +is not set to 1 then the network event hook will never be called. See +http://www.FreeRTOS.org/FreeRTOS-Plus/FreeRTOS_Plus_UDP/API/vApplicationIPNetworkEventHook.shtml +*/ +#define ipconfigUSE_NETWORK_EVENT_HOOK 1 + +/* Sockets have a send block time attribute. If FreeRTOS_sendto() is called but +a network buffer cannot be obtained then the calling task is held in the Blocked +state (so other tasks can continue to executed) until either a network buffer +becomes available or the send block time expires. If the send block time expires +then the send operation is aborted. The maximum allowable send block time is +capped to the value set by ipconfigMAX_SEND_BLOCK_TIME_TICKS. Capping the +maximum allowable send block time prevents prevents a deadlock occurring when +all the network buffers are in use and the tasks that process (and subsequently +free) the network buffers are themselves blocked waiting for a network buffer. +ipconfigMAX_SEND_BLOCK_TIME_TICKS is specified in RTOS ticks. A time in +milliseconds can be converted to a time in ticks by dividing the time in +milliseconds by portTICK_PERIOD_MS. */ +#define ipconfigUDP_MAX_SEND_BLOCK_TIME_TICKS ( 5000U / portTICK_PERIOD_MS ) + +/* If ipconfigUSE_DHCP is 1 then FreeRTOS+TCP will attempt to retrieve an IP +address, netmask, DNS server address and gateway address from a DHCP server. If +ipconfigUSE_DHCP is 0 then FreeRTOS+TCP will use a static IP address. The +stack will revert to using the static IP address even when ipconfigUSE_DHCP is +set to 1 if a valid configuration cannot be obtained from a DHCP server for any +reason. The static configuration used is that passed into the stack by the +FreeRTOS_IPInit() function call. */ +#define ipconfigUSE_DHCP 1 + +/* When ipconfigUSE_DHCP is set to 1, DHCP requests will be sent out at +increasing time intervals until either a reply is received from a DHCP server +and accepted, or the interval between transmissions reaches +ipconfigMAXIMUM_DISCOVER_TX_PERIOD. The IP stack will revert to using the +static IP address passed as a parameter to FreeRTOS_IPInit() if the +re-transmission time interval reaches ipconfigMAXIMUM_DISCOVER_TX_PERIOD without +a DHCP reply being received. */ +#define ipconfigMAXIMUM_DISCOVER_TX_PERIOD ( 120000U / portTICK_PERIOD_MS ) + +/* The ARP cache is a table that maps IP addresses to MAC addresses. The IP +stack can only send a UDP message to a remove IP address if it knowns the MAC +address associated with the IP address, or the MAC address of the router used to +contact the remote IP address. When a UDP message is received from a remote IP +address the MAC address and IP address are added to the ARP cache. When a UDP +message is sent to a remote IP address that does not already appear in the ARP +cache then the UDP message is replaced by a ARP message that solicits the +required MAC address information. ipconfigARP_CACHE_ENTRIES defines the maximum +number of entries that can exist in the ARP table at any one time. */ +#define ipconfigARP_CACHE_ENTRIES 6 + +/* ARP requests that do not result in an ARP response will be re-transmitted a +maximum of ipconfigMAX_ARP_RETRANSMISSIONS times before the ARP request is +aborted. */ +#define ipconfigMAX_ARP_RETRANSMISSIONS ( 5 ) + +/* ipconfigMAX_ARP_AGE defines the maximum time between an entry in the ARP +table being created or refreshed and the entry being removed because it is stale. +New ARP requests are sent for ARP cache entries that are nearing their maximum +age. ipconfigMAX_ARP_AGE is specified in tens of seconds, so a value of 150 is +equal to 1500 seconds (or 25 minutes). */ +#define ipconfigMAX_ARP_AGE 150 + +/* Implementing FreeRTOS_inet_addr() necessitates the use of string handling +routines, which are relatively large. To save code space the full +FreeRTOS_inet_addr() implementation is made optional, and a smaller and faster +alternative called FreeRTOS_inet_addr_quick() is provided. FreeRTOS_inet_addr() +takes an IP in decimal dot format (for example, "192.168.0.1") as its parameter. +FreeRTOS_inet_addr_quick() takes an IP address as four separate numerical octets +(for example, 192, 168, 0, 1) as its parameters. If +ipconfigINCLUDE_FULL_INET_ADDR is set to 1 then both FreeRTOS_inet_addr() and +FreeRTOS_indet_addr_quick() are available. If ipconfigINCLUDE_FULL_INET_ADDR is +not set to 1 then only FreeRTOS_indet_addr_quick() is available. */ +#define ipconfigINCLUDE_FULL_INET_ADDR 0 + +/* ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS defines the total number of network buffer that +are available to the IP stack. The total number of network buffers is limited +to ensure the total amount of RAM that can be consumed by the IP stack is capped +to a pre-determinable value. */ +#define ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS 60 + +/* A FreeRTOS queue is used to send events from application tasks to the IP +stack. ipconfigEVENT_QUEUE_LENGTH sets the maximum number of events that can +be queued for processing at any one time. The event queue must be a minimum of +5 greater than the total number of network buffers. */ +#define ipconfigEVENT_QUEUE_LENGTH ( ipconfigNUM_NETWORK_BUFFER_DESCRIPTORS + 5 ) + +/* The address of a socket is the combination of its IP address and its port +number. FreeRTOS_bind() is used to manually allocate a port number to a socket +(to 'bind' the socket to a port), but manual binding is not normally necessary +for client sockets (those sockets that initiate outgoing connections rather than +wait for incoming connections on a known port number). If +ipconfigALLOW_SOCKET_SEND_WITHOUT_BIND is set to 1 then calling +FreeRTOS_sendto() on a socket that has not yet been bound will result in the IP +stack automatically binding the socket to a port number from the range +socketAUTO_PORT_ALLOCATION_START_NUMBER to 0xffff. If +ipconfigALLOW_SOCKET_SEND_WITHOUT_BIND is set to 0 then calling FreeRTOS_sendto() +on a socket that has not yet been bound will result in the send operation being +aborted. */ +#define ipconfigALLOW_SOCKET_SEND_WITHOUT_BIND 1 + +/* Defines the Time To Live (TTL) values used in outgoing UDP packets. */ +#define ipconfigUDP_TIME_TO_LIVE 128 +#define ipconfigTCP_TIME_TO_LIVE 128 /* also defined in FreeRTOSIPConfigDefaults.h */ + +/* USE_TCP: Use TCP and all its features */ +#define ipconfigUSE_TCP ( 1 ) + +/* USE_WIN: Let TCP use windowing mechanism. */ +#define ipconfigUSE_TCP_WIN ( 1 ) + +/* The MTU is the maximum number of bytes the payload of a network frame can +contain. For normal Ethernet V2 frames the maximum MTU is 1500. Setting a +lower value can save RAM, depending on the buffer management scheme used. If +ipconfigCAN_FRAGMENT_OUTGOING_PACKETS is 1 then (ipconfigNETWORK_MTU - 28) must +be divisible by 8. */ +#define ipconfigNETWORK_MTU 1200U + +/* Set ipconfigUSE_DNS to 1 to include a basic DNS client/resolver. DNS is used +through the FreeRTOS_gethostbyname() API function. */ +#define ipconfigUSE_DNS 0 + +/* If ipconfigREPLY_TO_INCOMING_PINGS is set to 1 then the IP stack will +generate replies to incoming ICMP echo (ping) requests. */ +#define ipconfigREPLY_TO_INCOMING_PINGS 1 + +/* If ipconfigSUPPORT_OUTGOING_PINGS is set to 1 then the +FreeRTOS_SendPingRequest() API function is available. */ +#define ipconfigSUPPORT_OUTGOING_PINGS 0 + +/* If ipconfigSUPPORT_SELECT_FUNCTION is set to 1 then the FreeRTOS_select() +(and associated) API function is available. */ +#define ipconfigSUPPORT_SELECT_FUNCTION 1 + +/* If ipconfigFILTER_OUT_NON_ETHERNET_II_FRAMES is set to 1 then Ethernet frames +that are not in Ethernet II format will be dropped. This option is included for +potential future IP stack developments. */ +#define ipconfigFILTER_OUT_NON_ETHERNET_II_FRAMES 1 + +/* If ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES is set to 1 then it is the +responsibility of the Ethernet interface to filter out packets that are of no +interest. If the Ethernet interface does not implement this functionality, then +set ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES to 0 to have the IP stack +perform the filtering instead (it is much less efficient for the stack to do it +because the packet will already have been passed into the stack). If the +Ethernet driver does all the necessary filtering in hardware then software +filtering can be removed by using a value other than 1 or 0. */ +#define ipconfigETHERNET_DRIVER_FILTERS_FRAME_TYPES 1 + +/* The Linux simulator cannot really simulate MAC interrupts, and needs to +block occasionally to allow other tasks to run. */ +#define configWINDOWS_MAC_INTERRUPT_SIMULATOR_DELAY ( 20 / portTICK_PERIOD_MS ) + +/* Advanced only: in order to access 32-bit fields in the IP packets with +32-bit memory instructions, all packets will be stored 32-bit-aligned, plus 16-bits. +This has to do with the contents of the IP-packets: all 32-bit fields are +32-bit-aligned, plus 16-bit(!) */ +#define ipconfigPACKET_FILLER_SIZE 2U + +/* Define the size of the pool of TCP window descriptors. On the average, each +TCP socket will use up to 2 x 6 descriptors, meaning that it can have 2 x 6 +outstanding packets (for Rx and Tx). When using up to 10 TP sockets +simultaneously, one could define TCP_WIN_SEG_COUNT as 120. */ +#define ipconfigTCP_WIN_SEG_COUNT 240 + +/* Each TCP socket has a circular buffers for Rx and Tx, which have a fixed +maximum size. Define the size of Rx buffer for TCP sockets. */ +#define ipconfigTCP_RX_BUFFER_LENGTH ( 10000 ) + +/* Define the size of Tx buffer for TCP sockets. */ +#define ipconfigTCP_TX_BUFFER_LENGTH ( 10000 ) + +/* When using call-back handlers, the driver may check if the handler points to +real program memory (RAM or flash) or just has a random non-zero value. */ +#define ipconfigIS_VALID_PROG_ADDRESS(x) ( (x) != NULL ) + +/* Include support for TCP hang protection. All sockets in a connecting or +disconnecting stage will timeout after a period of non-activity. */ +#define ipconfigTCP_HANG_PROTECTION ( 0 ) +#define ipconfigTCP_HANG_PROTECTION_TIME ( 30 ) + +/* Include support for TCP keep-alive messages. */ +#define ipconfigTCP_KEEP_ALIVE ( 1 ) +#define ipconfigTCP_KEEP_ALIVE_INTERVAL ( 20 ) /* in seconds */ + +#define portINLINE __inline + +// suggested by https://github.com/FreeRTOS/FreeRTOS-Plus-TCP/tree/main/source/portable/NetworkInterface/STM32Fxx +#define ipconfigMAC_INTERRUPT_PRIORITY (configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY + 1) +#define ipconfigUSE_RMII 1 +#define ipconfigDRIVER_INCLUDED_TX_IP_CHECKSUM 1 +#define ipconfigZERO_COPY_RX_DRIVER 1 +#define ipconfigZERO_COPY_TX_DRIVER 1 +#define ipconfigUSE_LINKED_RX_MESSAGES 1 + +// phyhandling.c will start searching for a PHY from address 0, trying these many addresses ("ports") +#define ipconfigPHY_MAX_PORTS 1 // we know LAN8724A in this board is at address 0, so one "port" is enough + +#endif /* FREERTOS_IP_CONFIG_H */ diff --git a/examples/stm32/nucleo-f746zg-freertos-tcp/Makefile b/examples/stm32/nucleo-f746zg-freertos-tcp/Makefile new file mode 100644 index 00000000..b4057a19 --- /dev/null +++ b/examples/stm32/nucleo-f746zg-freertos-tcp/Makefile @@ -0,0 +1,73 @@ +CFLAGS = -W -Wall -Wextra -Werror -Wundef -Wshadow -Wdouble-promotion +CFLAGS += -Wformat-truncation -fno-common -Wconversion -Wno-sign-conversion +CFLAGS += -g3 -Os -ffunction-sections -fdata-sections +CFLAGS += -I. -Icmsis_core/CMSIS/Core/Include -Icmsis_f7/Include +CFLAGS += -mcpu=cortex-m7 -mthumb -mfloat-abi=hard -mfpu=fpv5-sp-d16 +LDFLAGS ?= -Tlink.ld -nostdlib -nostartfiles --specs nano.specs -lc -lgcc -Wl,--gc-sections -Wl,-Map=$@.map + +SOURCES = main.c syscalls.c sysinit.c +SOURCES += cmsis_f7/Source/Templates/gcc/startup_stm32f746xx.s # ST startup file. Compiler-dependent! + +# FreeRTOS +SOURCES += FreeRTOS-Kernel/portable/MemMang/heap_4.c +SOURCES += FreeRTOS-Kernel/portable/GCC/ARM_CM7/r0p1/port.c +CFLAGS += -IFreeRTOS-Kernel/include +CFLAGS += -IFreeRTOS-Kernel/portable/GCC/ARM_CM7/r0p1 -Wno-conversion + +# FreeRTOS-Plus-TCP +SOURCES += $(wildcard FreeRTOS-TCP/source/*.c) +SOURCES += FreeRTOS-TCP/source/portable/BufferManagement/BufferAllocation_2.c +SOURCES += FreeRTOS-TCP/source/portable/NetworkInterface/Common/phyHandling.c +SOURCES += FreeRTOS-TCP/source/portable/NetworkInterface/STM32Fxx/NetworkInterface.c +SOURCES += FreeRTOS-TCP/source/portable/NetworkInterface/STM32Fxx/stm32fxx_hal_eth.c +CFLAGS += -IFreeRTOS-TCP/source/include +CFLAGS += -IFreeRTOS-TCP/source/portable/Compiler/GCC +CFLAGS += -IFreeRTOS-TCP/source/portable/NetworkInterface/include +CFLAGS += -IFreeRTOS-TCP/source/portable/NetworkInterface/STM32Fxx +CFLAGS += -DSTM32F7xx -Wno-unused-parameter + +# HAL +CFLAGS += -DSTM32F746xx -Wno-sign-compare -Wno-undef -Wno-shadow -Wno-array-bounds -Wno-error + +SOURCES += mongoose.c net.c packed_fs.c +CFLAGS += $(CFLAGS_EXTRA) # Mongoose options are defined in mongoose_custom.h + +ifeq ($(OS),Windows_NT) + RM = cmd /C del /Q /F /S +else + RM = rm -rf +endif + +all build example: firmware.bin + +firmware.bin: firmware.elf + arm-none-eabi-objcopy -O binary $< $@ + +firmware.elf: FreeRTOS-TCP FreeRTOS-Kernel cmsis_core cmsis_f7 $(SOURCES) hal.h link.ld + arm-none-eabi-gcc $(SOURCES) $(wildcard FreeRTOS-Kernel/*.c) $(CFLAGS) $(LDFLAGS) -o $@ + +flash: firmware.bin + st-flash --reset write $< 0x8000000 + +cmsis_core: # ARM CMSIS core headers + git clone --depth 1 -b 5.9.0 https://github.com/ARM-software/CMSIS_5 $@ +cmsis_f7: # ST CMSIS headers for STM32F7 series + git clone --depth 1 -b v1.2.8 https://github.com/STMicroelectronics/cmsis_device_f7 $@ +FreeRTOS-Kernel: # FreeRTOS sources + git clone --depth 1 -b V10.5.0 https://github.com/FreeRTOS/FreeRTOS-Kernel $@ +FreeRTOS-TCP: # FreeRTOS-Plus-TCP sources + git clone --depth 1 -b V3.1.0 https://github.com/FreeRTOS/FreeRTOS-Plus-TCP $@ + +# Automated remote test. Requires env variable VCON_API_KEY set. See https://vcon.io/automated-firmware-tests/ +DEVICE_URL ?= https://dash.vcon.io/api/v3/devices/5 +update: firmware.bin + curl --fail-with-body -su :$(VCON_API_KEY) $(DEVICE_URL)/ota --data-binary @$< + +test update: CFLAGS_EXTRA += -DUART_DEBUG=USART1 +test: update + curl --fail-with-body -su :$(VCON_API_KEY) $(DEVICE_URL)/tx?t=5 | tee /tmp/output.txt + grep 'READY, IP:' /tmp/output.txt # Check for network init + grep 'MQTT connected' /tmp/output.txt # Check for MQTT connection success + +clean: + $(RM) firmware.* *.su cmsis_core cmsis_f7 FreeRTOS-Kernel FreeRTOS-TCP diff --git a/examples/stm32/nucleo-f746zg-freertos-tcp/README.md b/examples/stm32/nucleo-f746zg-freertos-tcp/README.md new file mode 100644 index 00000000..49aeaebb --- /dev/null +++ b/examples/stm32/nucleo-f746zg-freertos-tcp/README.md @@ -0,0 +1,3 @@ +# FreeRTOS-Plus-TCP Web device dashboard on NUCLEO-F746ZG + + diff --git a/examples/stm32/nucleo-f746zg-freertos-tcp/hal.h b/examples/stm32/nucleo-f746zg-freertos-tcp/hal.h new file mode 100644 index 00000000..fc84c5a5 --- /dev/null +++ b/examples/stm32/nucleo-f746zg-freertos-tcp/hal.h @@ -0,0 +1,150 @@ +// Copyright (c) 2022-23 Cesanta Software Limited +// All rights reserved +// https://www.st.com/resource/en/reference_manual/dm00124865-stm32f75xxx-and-stm32f74xxx-advanced-arm-based-32-bit-mcus-stmicroelectronics.pdf + +#pragma once + +#include + +#include +#include +#include +#include + +#define BIT(x) (1UL << (x)) +#define SETBITS(R, CLEARMASK, SETMASK) (R) = ((R) & ~(CLEARMASK)) | (SETMASK) +#define PIN(bank, num) ((((bank) - 'A') << 8) | (num)) +#define PINNO(pin) (pin & 255) +#define PINBANK(pin) (pin >> 8) + +/* System clock +5.3.3: APB1 clock <= 54MHz; APB2 clock <= 108MHz +3.3.2, Table 5: configure flash latency (WS) in accordance to clock freq +38.4: The AHB clock frequency must be at least 25 MHz when the Ethernet +controller is used */ +enum { APB1_PRE = 5 /* AHB clock / 4 */, APB2_PRE = 4 /* AHB clock / 2 */ }; +enum { PLL_HSI = 16, PLL_M = 8, PLL_N = 216, PLL_P = 2 }; // Run at 216 Mhz +#define FLASH_LATENCY 7 +#define SYS_FREQUENCY ((PLL_HSI * PLL_N / PLL_M / PLL_P) * 1000000) +#define APB2_FREQUENCY (SYS_FREQUENCY / (BIT(APB2_PRE - 3))) +#define APB1_FREQUENCY (SYS_FREQUENCY / (BIT(APB1_PRE - 3))) + +static inline void spin(volatile uint32_t count) { + while (count--) (void) 0; +} + +enum { GPIO_MODE_INPUT, GPIO_MODE_OUTPUT, GPIO_MODE_AF, GPIO_MODE_ANALOG }; +enum { GPIO_OTYPE_PUSH_PULL, GPIO_OTYPE_OPEN_DRAIN }; +enum { GPIO_SPEED_LOW, GPIO_SPEED_MEDIUM, GPIO_SPEED_HIGH, GPIO_SPEED_INSANE }; +enum { GPIO_PULL_NONE, GPIO_PULL_UP, GPIO_PULL_DOWN }; +#define GPIO(N) ((GPIO_TypeDef *) (0x40020000 + 0x400 * (N))) + +static GPIO_TypeDef *gpio_bank(uint16_t pin) { + return GPIO(PINBANK(pin)); +} +static inline void gpio_toggle(uint16_t pin) { + GPIO_TypeDef *gpio = gpio_bank(pin); + uint32_t mask = BIT(PINNO(pin)); + gpio->BSRR = mask << (gpio->ODR & mask ? 16 : 0); +} +static inline int gpio_read(uint16_t pin) { + return gpio_bank(pin)->IDR & BIT(PINNO(pin)) ? 1 : 0; +} +static inline void gpio_write(uint16_t pin, bool val) { + GPIO_TypeDef *gpio = gpio_bank(pin); + gpio->BSRR = BIT(PINNO(pin)) << (val ? 0 : 16); +} +static inline void gpio_init(uint16_t pin, uint8_t mode, uint8_t type, + uint8_t speed, uint8_t pull, uint8_t af) { + GPIO_TypeDef *gpio = gpio_bank(pin); + uint8_t n = (uint8_t) (PINNO(pin)); + RCC->AHB1ENR |= BIT(PINBANK(pin)); // Enable GPIO clock + SETBITS(gpio->OTYPER, 1UL << n, ((uint32_t) type) << n); + SETBITS(gpio->OSPEEDR, 3UL << (n * 2), ((uint32_t) speed) << (n * 2)); + SETBITS(gpio->PUPDR, 3UL << (n * 2), ((uint32_t) pull) << (n * 2)); + SETBITS(gpio->AFR[n >> 3], 15UL << ((n & 7) * 4), + ((uint32_t) af) << ((n & 7) * 4)); + SETBITS(gpio->MODER, 3UL << (n * 2), ((uint32_t) mode) << (n * 2)); +} +static inline void gpio_input(uint16_t pin) { + gpio_init(pin, GPIO_MODE_INPUT, GPIO_OTYPE_PUSH_PULL, GPIO_SPEED_HIGH, + GPIO_PULL_NONE, 0); +} +static inline void gpio_output(uint16_t pin) { + gpio_init(pin, GPIO_MODE_OUTPUT, GPIO_OTYPE_PUSH_PULL, GPIO_SPEED_HIGH, + GPIO_PULL_NONE, 0); +} + +static inline void irq_exti_attach(uint16_t pin) { + uint8_t bank = (uint8_t) (PINBANK(pin)), n = (uint8_t) (PINNO(pin)); + SYSCFG->EXTICR[n / 4] &= ~(15UL << ((n % 4) * 4)); + SYSCFG->EXTICR[n / 4] |= (uint32_t) (bank << ((n % 4) * 4)); + EXTI->IMR |= BIT(n); + EXTI->RTSR |= BIT(n); + EXTI->FTSR |= BIT(n); + int irqvec = n < 5 ? 6 + n : n < 10 ? 23 : 40; // IRQ vector index, 10.1.2 + NVIC_SetPriority(irqvec, 3); + NVIC_EnableIRQ(irqvec); +} + +#ifndef UART_DEBUG +#define UART_DEBUG USART3 +#endif + +static inline void uart_init(USART_TypeDef *uart, unsigned long baud) { + // https://www.st.com/resource/en/datasheet/stm32f746zg.pdf + uint8_t af = 7; // Alternate function + uint16_t rx = 0, tx = 0; // pins + uint32_t freq = 0; // Bus frequency. UART1 is on APB2, rest on APB1 + + if (uart == USART1) freq = APB2_FREQUENCY, RCC->APB2ENR |= BIT(4); + if (uart == USART2) freq = APB1_FREQUENCY, RCC->APB1ENR |= BIT(17); + if (uart == USART3) freq = APB1_FREQUENCY, RCC->APB1ENR |= BIT(18); + + if (uart == USART1) tx = PIN('A', 9), rx = PIN('A', 10); + if (uart == USART2) tx = PIN('A', 2), rx = PIN('A', 3); + if (uart == USART3) tx = PIN('D', 8), rx = PIN('D', 9); + + gpio_init(tx, GPIO_MODE_AF, GPIO_OTYPE_PUSH_PULL, GPIO_SPEED_HIGH, 0, af); + gpio_init(rx, GPIO_MODE_AF, GPIO_OTYPE_PUSH_PULL, GPIO_SPEED_HIGH, 0, af); + uart->CR1 = 0; // Disable this UART + uart->BRR = freq / baud; // Set baud rate + uart->CR1 |= BIT(0) | BIT(2) | BIT(3); // Set UE, RE, TE +} +static inline void uart_write_byte(USART_TypeDef *uart, uint8_t byte) { + uart->TDR = byte; + while ((uart->ISR & BIT(7)) == 0) spin(1); +} +static inline void uart_write_buf(USART_TypeDef *uart, char *buf, size_t len) { + while (len-- > 0) uart_write_byte(uart, *(uint8_t *) buf++); +} +static inline int uart_read_ready(USART_TypeDef *uart) { + return uart->ISR & BIT(5); // If RXNE bit is set, data is ready +} +static inline uint8_t uart_read_byte(USART_TypeDef *uart) { + return (uint8_t) (uart->RDR & 255); +} + +static inline void rng_init(void) { + RCC->AHB2ENR |= RCC_AHB2ENR_RNGEN; + RNG->CR |= RNG_CR_RNGEN; +} +static inline uint32_t rng_read(void) { + while ((RNG->SR & RNG_SR_DRDY) == 0) (void) 0; + return RNG->DR; +} + +#define UUID ((uint8_t *) UID_BASE) // Unique 96-bit chip ID. TRM 41.1 + +// Helper macro for MAC generation +#define GENERATE_LOCALLY_ADMINISTERED_MAC() \ + { \ + 2, UUID[0] ^ UUID[1], UUID[2] ^ UUID[3], UUID[4] ^ UUID[5], \ + UUID[6] ^ UUID[7] ^ UUID[8], UUID[9] ^ UUID[10] ^ UUID[11] \ + } + +extern uint32_t ticks; + +static inline uint32_t ticks_get(void) { + return ticks; +} diff --git a/examples/stm32/nucleo-f746zg-freertos-tcp/link.ld b/examples/stm32/nucleo-f746zg-freertos-tcp/link.ld new file mode 100644 index 00000000..330baddd --- /dev/null +++ b/examples/stm32/nucleo-f746zg-freertos-tcp/link.ld @@ -0,0 +1,29 @@ +ENTRY(Reset_Handler); +MEMORY { + flash(rx) : ORIGIN = 0x08000000, LENGTH = 1024k + sram(rwx) : ORIGIN = 0x20000000, LENGTH = 320k +} +_estack = ORIGIN(sram) + LENGTH(sram); /* stack points to end of SRAM */ + +SECTIONS { + .vectors : { KEEP(*(.isr_vector)) } > flash + .text : { *(.text* .text.*) } > flash + .rodata : { *(.rodata*) } > flash + + .data : { + _sdata = .; /* for init_ram() */ + *(.first_data) + *(.data SORT(.data.*)) + _edata = .; /* for init_ram() */ + } > sram AT > flash + _sidata = LOADADDR(.data); + + .bss : { + _sbss = .; /* for init_ram() */ + *(.bss SORT(.bss.*) COMMON) + _ebss = .; /* for init_ram() */ + } > sram + + . = ALIGN(8); + _end = .; /* for cmsis_gcc.h and init_ram() */ +} diff --git a/examples/stm32/nucleo-f746zg-freertos-tcp/main.c b/examples/stm32/nucleo-f746zg-freertos-tcp/main.c new file mode 100644 index 00000000..e05baa65 --- /dev/null +++ b/examples/stm32/nucleo-f746zg-freertos-tcp/main.c @@ -0,0 +1,119 @@ +// Copyright (c) 2023 Cesanta Software Limited +// All rights reserved + +#include "hal.h" +#include "mongoose.h" + +#define LED1 PIN('B', 0) // On-board LED pin (green) +#define LED2 PIN('B', 7) // On-board LED pin (blue) +#define LED3 PIN('B', 14) // On-board LED pin (red) + +#define LED LED2 // Use blue LED for blinking +#define BLINK_PERIOD_MS 1000 // LED blinking period in millis + +uint32_t ticks; // serve a tick counter for HAL functions +extern void xPortSysTickHandler(void); +void SysTick_Handler(void) { + // serve ticks for HAL functions, is simpler + ++ticks; + // xPortSysTickHandler() must be called after vTaskStartScheduler(), + // initialization is fast and in practice this check is not needed + if (xTaskGetSchedulerState() != taskSCHEDULER_NOT_STARTED) + xPortSysTickHandler(); +} + +void mg_random(void *buf, size_t len) { // Use on-board RNG + for (size_t n = 0; n < len; n += sizeof(uint32_t)) { + uint32_t r = rng_read(); + memcpy((char *) buf + n, &r, n + sizeof(r) > len ? len - n : sizeof(r)); + } +} + +static void ethernet_init(void) { + // Initialise Ethernet. Enable MAC GPIO pins, see + // https://www.farnell.com/datasheets/2014265.pdf section 6.10 + uint16_t pins[] = {PIN('A', 1), PIN('A', 2), PIN('A', 7), + PIN('B', 13), PIN('C', 1), PIN('C', 4), + PIN('C', 5), PIN('G', 11), PIN('G', 13)}; + for (size_t i = 0; i < sizeof(pins) / sizeof(pins[0]); i++) { + gpio_init(pins[i], GPIO_MODE_AF, GPIO_OTYPE_PUSH_PULL, GPIO_SPEED_INSANE, + GPIO_PULL_NONE, 11); // 11 is the Ethernet function + } + NVIC_SetPriority(ETH_IRQn, ipconfigMAC_INTERRUPT_PRIORITY); + NVIC_EnableIRQ(ETH_IRQn); // Setup Ethernet IRQ handler + SYSCFG->PMC |= SYSCFG_PMC_MII_RMII_SEL; // Use RMII. Goes first! + RCC->AHB1ENR |= + RCC_AHB1ENR_ETHMACEN | RCC_AHB1ENR_ETHMACTXEN | RCC_AHB1ENR_ETHMACRXEN; +} + +static void server(void *args) { + struct mg_mgr mgr; // Initialise Mongoose event manager + mg_mgr_init(&mgr); // and attach it to the interface + mg_log_set(MG_LL_DEBUG); // Set log level + + MG_INFO(("Initialising application...")); + extern void device_dashboard_fn(struct mg_connection *, int, void *, void *); + mg_http_listen(&mgr, "http://0.0.0.0", device_dashboard_fn, NULL); + + MG_INFO(("Starting event loop")); + for (;;) mg_mgr_poll(&mgr, 1000); // Infinite event loop + (void) args; +} + +static void blinker(void *args) { + gpio_init(LED, GPIO_MODE_OUTPUT, GPIO_OTYPE_PUSH_PULL, GPIO_SPEED_MEDIUM, + GPIO_PULL_NONE, 0); + for (;;) { + gpio_toggle(LED); + vTaskDelay(pdMS_TO_TICKS(BLINK_PERIOD_MS)); + } + (void) args; +} + +// https://www.freertos.org/FreeRTOS-Plus/FreeRTOS_Plus_TCP/TCP_Networking_Tutorial_Initialising_TCP.html +void vApplicationIPNetworkEventHook(eIPCallbackEvent_t ev) { + static bool mongoose_started = false; + MG_INFO(("FreeRTOS-Plus-TCP net event: %d", ev)); + if (ev == eNetworkUp && mongoose_started == false) { + uint32_t ip = FreeRTOS_GetIPAddress(); + MG_INFO(("READY, IP: %M", mg_print_ip4, &ip)); + xTaskCreate(server, "server", 2048, 0, configMAX_PRIORITIES - 1, NULL); + mongoose_started = true; + } +} + +int main(void) { + uart_init(UART_DEBUG, 115200); // Initialise UART + + uint8_t macaddr[6] = GENERATE_LOCALLY_ADMINISTERED_MAC(); + // required for fallback if DHCP fails + static const uint8_t ipaddr[4] = {192, 168, 0, 77}; + static const uint8_t netmask[4] = {255, 255, 255, 0}; + static const uint8_t dnsaddr[4] = {8, 8, 8, 8}; + static const uint8_t gwaddr[4] = {192, 168, 0, 1}; + FreeRTOS_IPInit(ipaddr, netmask, gwaddr, dnsaddr, macaddr); + MG_INFO(("MAC: %M. Waiting for IP...", mg_print_mac, macaddr)); + + // Start tasks. NOTE: stack sizes are in 32-bit words + xTaskCreate(blinker, "blinker", 128, ":)", configMAX_PRIORITIES - 1, NULL); + + vTaskStartScheduler(); // This blocks + return 0; +} + +// Hooks for FreeRTOS-Plus-TCP network interface +#include "stm32fxx_hal_eth.h" +void HAL_ETH_MspInit(ETH_HandleTypeDef *heth) { + if (heth->Instance == ETH) ethernet_init(); +} + +uint32_t ulApplicationGetNextSequenceNumber(uint32_t a, uint16_t b, uint32_t c, + uint16_t d) { + (void) a, (void) b, (void) c, (void) d; + return rng_read(); +} + +BaseType_t xApplicationGetRandomNumber(uint32_t *p) { + *p = rng_read(); + return pdTRUE; +} diff --git a/examples/stm32/nucleo-f746zg-freertos-tcp/mongoose.c b/examples/stm32/nucleo-f746zg-freertos-tcp/mongoose.c new file mode 120000 index 00000000..5e522bbc --- /dev/null +++ b/examples/stm32/nucleo-f746zg-freertos-tcp/mongoose.c @@ -0,0 +1 @@ +../../../mongoose.c \ No newline at end of file diff --git a/examples/stm32/nucleo-f746zg-freertos-tcp/mongoose.h b/examples/stm32/nucleo-f746zg-freertos-tcp/mongoose.h new file mode 120000 index 00000000..ee4ac823 --- /dev/null +++ b/examples/stm32/nucleo-f746zg-freertos-tcp/mongoose.h @@ -0,0 +1 @@ +../../../mongoose.h \ No newline at end of file diff --git a/examples/stm32/nucleo-f746zg-freertos-tcp/mongoose_custom.h b/examples/stm32/nucleo-f746zg-freertos-tcp/mongoose_custom.h new file mode 100644 index 00000000..08e7eff9 --- /dev/null +++ b/examples/stm32/nucleo-f746zg-freertos-tcp/mongoose_custom.h @@ -0,0 +1,8 @@ +#pragma once + +// See https://mongoose.ws/documentation/#build-options +#define MG_ARCH MG_ARCH_FREERTOS +#define MG_ENABLE_FREERTOS_TCP 1 +#define MG_ENABLE_CUSTOM_RANDOM 1 +#define MG_ENABLE_PACKED_FS 1 + diff --git a/examples/stm32/nucleo-f746zg-freertos-tcp/net.c b/examples/stm32/nucleo-f746zg-freertos-tcp/net.c new file mode 120000 index 00000000..fe0e6f06 --- /dev/null +++ b/examples/stm32/nucleo-f746zg-freertos-tcp/net.c @@ -0,0 +1 @@ +../../device-dashboard/net.c \ No newline at end of file diff --git a/examples/stm32/nucleo-f746zg-freertos-tcp/packed_fs.c b/examples/stm32/nucleo-f746zg-freertos-tcp/packed_fs.c new file mode 120000 index 00000000..e06bf092 --- /dev/null +++ b/examples/stm32/nucleo-f746zg-freertos-tcp/packed_fs.c @@ -0,0 +1 @@ +../../device-dashboard/packed_fs.c \ No newline at end of file diff --git a/examples/stm32/nucleo-f746zg-freertos-tcp/stm32f7xx_hal.h b/examples/stm32/nucleo-f746zg-freertos-tcp/stm32f7xx_hal.h new file mode 100644 index 00000000..942ff22b --- /dev/null +++ b/examples/stm32/nucleo-f746zg-freertos-tcp/stm32f7xx_hal.h @@ -0,0 +1,59 @@ +#pragma once + +// provide some STM32 HAL definitions needed by the ETH module without actually +// including STM32 HAL + +#define HAL_ETH_MODULE_ENABLED +#define ETH_RX_BUF_SIZE ETH_MAX_PACKET_SIZE +#define ETH_TX_BUF_SIZE ETH_MAX_PACKET_SIZE +#define ETH_RXBUFNB ((uint32_t) 8) +#define ETH_TXBUFNB ((uint32_t) 4) + +#include "hal.h" +#include "stm32f7xx.h" + +typedef enum { + HAL_OK = 0, + HAL_ERROR = 1, + HAL_BUSY = 2, + HAL_TIMEOUT = 3 +} HAL_StatusTypeDef; + +typedef enum { HAL_UNLOCKED = 0, HAL_LOCKED = 1 } HAL_LockTypeDef; + +#define __HAL_LOCK(h) \ + do { \ + if ((h)->Lock == HAL_LOCKED) return HAL_BUSY; \ + (h)->Lock = HAL_LOCKED; \ + } while (0) + +#define __HAL_UNLOCK(h) \ + do { \ + (h)->Lock = HAL_UNLOCKED; \ + } while (0) + +#ifndef __weak +#define __weak __attribute__((weak)) +#endif +#ifndef __packed +#define __packed __attribute__((__packed__)) +#endif + +#define assert_param(expr) ((void) 0U) + +#define PHY_READ_TO ((uint32_t) 0x0000FFFF) +#define PHY_WRITE_TO ((uint32_t) 0x0000FFFF) + +// emulate STM32 HAL function calls + +// we already enabled it in SystemInit() in sysinit.c +#define __HAL_RCC_SYSCFG_CLK_ENABLE() + +// we set SystemCoreClock = SYS_FREQUENCY in sysinit.c +static inline uint32_t HAL_RCC_GetHCLKFreq(void) { + return SYS_FREQUENCY; +} + +static inline uint32_t HAL_GetTick(void) { + return ticks_get(); +} diff --git a/examples/stm32/nucleo-f746zg-freertos-tcp/syscalls.c b/examples/stm32/nucleo-f746zg-freertos-tcp/syscalls.c new file mode 100644 index 00000000..be3210aa --- /dev/null +++ b/examples/stm32/nucleo-f746zg-freertos-tcp/syscalls.c @@ -0,0 +1,85 @@ +#include + +#include "hal.h" + +int _fstat(int fd, struct stat *st) { + if (fd < 0) return -1; + st->st_mode = S_IFCHR; + return 0; +} + +void *_sbrk(int incr) { + extern char _end; + static unsigned char *heap = NULL; + unsigned char *prev_heap; + if (heap == NULL) heap = (unsigned char *) &_end; + prev_heap = heap; + heap += incr; + return prev_heap; +} + +int _open(const char *path) { + (void) path; + return -1; +} + +int _close(int fd) { + (void) fd; + return -1; +} + +int _isatty(int fd) { + (void) fd; + return 1; +} + +int _lseek(int fd, int ptr, int dir) { + (void) fd, (void) ptr, (void) dir; + return 0; +} + +void _exit(int status) { + (void) status; + for (;;) asm volatile("BKPT #0"); +} + +void _kill(int pid, int sig) { + (void) pid, (void) sig; +} + +int _getpid(void) { + return -1; +} + +int _write(int fd, char *ptr, int len) { + (void) fd, (void) ptr, (void) len; + if (fd == 1) uart_write_buf(UART_DEBUG, ptr, (size_t) len); + return -1; +} + +int _read(int fd, char *ptr, int len) { + (void) fd, (void) ptr, (void) len; + return -1; +} + +int _link(const char *a, const char *b) { + (void) a, (void) b; + return -1; +} + +int _unlink(const char *a) { + (void) a; + return -1; +} + +int _stat(const char *path, struct stat *st) { + (void) path, (void) st; + return -1; +} + +int mkdir(const char *path, mode_t mode) { + (void) path, (void) mode; + return -1; +} + +void _init(void) {} diff --git a/examples/stm32/nucleo-f746zg-freertos-tcp/sysinit.c b/examples/stm32/nucleo-f746zg-freertos-tcp/sysinit.c new file mode 100644 index 00000000..5e65284e --- /dev/null +++ b/examples/stm32/nucleo-f746zg-freertos-tcp/sysinit.c @@ -0,0 +1,29 @@ +// Copyright (c) 2023 Cesanta Software Limited +// All rights reserved +// +// This file contains essentials required by the CMSIS: +// uint32_t SystemCoreClock - holds the system core clock value +// SystemInit() - initialises the system, e.g. sets up clocks + +#include "hal.h" + +uint32_t SystemCoreClock = SYS_FREQUENCY; + +void SystemInit(void) { // Called automatically by startup code + SCB->CPACR |= ((3UL << 10 * 2) | (3UL << 11 * 2)); // Enable FPU + asm("DSB"); + asm("ISB"); + FLASH->ACR |= FLASH_LATENCY | BIT(8) | BIT(9); // Flash latency, prefetch + RCC->PLLCFGR &= ~((BIT(17) - 1)); // Clear PLL multipliers + RCC->PLLCFGR |= (((PLL_P - 2) / 2) & 3) << 16; // Set PLL_P + RCC->PLLCFGR |= PLL_M | (PLL_N << 6); // Set PLL_M and PLL_N + RCC->CR |= BIT(24); // Enable PLL + while ((RCC->CR & BIT(25)) == 0) spin(1); // Wait until done + RCC->CFGR = (APB1_PRE << 10) | (APB2_PRE << 13); // Set prescalers + RCC->CFGR |= 2; // Set clock source to PLL + while ((RCC->CFGR & 12) == 0) spin(1); // Wait until done + + RCC->APB2ENR |= RCC_APB2ENR_SYSCFGEN; // Enable SYSCFG + rng_init(); // Initialise random number generator + SysTick_Config(SystemCoreClock / 1000); // Sys tick every 1ms +}