diff --git a/examples/projects/product/README.md b/examples/projects/product/README.md index e69de29bb..fc5d11cbf 100644 --- a/examples/projects/product/README.md +++ b/examples/projects/product/README.md @@ -0,0 +1,44 @@ +Luos logo + +![](https://github.com/Luos-io/luos_engine/actions/workflows/build.yml/badge.svg) +[![](https://img.shields.io/github/license/Luos-io/luos_engine)](https://github.com/Luos-io/luos_engine/blob/master/LICENSE) + +[![](https://img.shields.io/badge/Luos-Documentation-34A3B4)](https://www.luos.io) +[![PlatformIO Registry](https://badges.registry.platformio.org/packages/luos/library/luos_engine.svg)](https://registry.platformio.org/libraries/luos_engine/luos_engine) + +[![](https://img.shields.io/discord/902486791658041364?label=Discord&logo=discord&style=social)](https://discord.gg/luos) +[![](https://img.shields.io/badge/LinkedIn-Share-0077B5?style=social&logo=linkedin)](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fgithub.com%2Fluos-io) + +# The complete product example :bulb: + +This example demonstrates how to deal with a real life project using Luos_engine. This code folder deals with custom types, custom messages commands, and demonstrate how to adapt your gate and pyluos to properly handle it. + +This project is a laser Galvo controller example that can be used in an engraving machine, a small surface laser cutter or a laser show device. +This has been tested with the great [interface board made by the opengalvo OPAL project](https://github.com/leswright1977/OPAL_PCB) on STM32-L476RG and a simple cat laser pointer toy. + +![The demonstration of a running galvo with a nucleo-L476RG.](galvo_demo.gif) + +This product is composed of multiple nodes: + +- A gate node called `custom_gate` running on your computer +- A laser Galvo node called `laser_galvo` running on a microcontroller (tested on STM32-L476RG, but it should work on most microcontrollers within the STM32 family). + +In this folder, you can also find a Python notebook `laser_galvo_control.ipynb` to control the laser Galvo. + +To learn more about how to deal with complete product project with Luos please read our [code organization documentation](https://www.luos.io/docs/luos-technology/basics/organization). + +## How to use :computer: + +1. Download and install [Platformio](https://platformio.org/platformio-ide) +2. Open the `custom_gate` folder into Platformio +3. Build (Platformio will do the rest) +4. Open the `laser_galvo` folder into Platformio +5. Build and flash the board (Platformio will do the rest) (of course your board with the galvo should be connected to your computer) +6. Run the `custom_gate` program in `custom_gate/.pio/build/native_serial/program` (or `custom_gate/.pio/build/native_serial/program.exe` if you use windows) +7. Install python requirements with `pip install -r requirements.txt` +8. Then you can play with the Ipython notebook `laser_galvo_control.ipynb` to control the laser Galvo + +## Don't hesitate to read [our documentation](https://www.luos.io/docs/luos-technology), or to post your questions/issues on the [Luos' community](https://discord.gg/luos). :books: + +[![](https://img.shields.io/badge/Luos-Documentation-34A3B4)](https://www.luos.io) +[![](https://img.shields.io/badge/LinkedIn-Follow%20us-0077B5?style=flat&logo=linkedin)](https://www.linkedin.com/company/luos) diff --git a/examples/projects/product/custom_gate/node_config.h b/examples/projects/product/custom_gate/node_config.h index 940439740..977c17022 100644 --- a/examples/projects/product/custom_gate/node_config.h +++ b/examples/projects/product/custom_gate/node_config.h @@ -113,6 +113,6 @@ #define SERIAL_RX_BUFFER_SIZE 65000 #define INIT_TIME 150 #define GATE_REFRESH_TIME_S 0.05f -#define SERIAL_PORT "/dev/cu.usbmodem1202" // "/dev/cu.usbserial-D308N897" +#define SERIAL_PORT "/dev/cu.usbmodem1102" // "/dev/cu.usbserial-D308N897" #endif /* _NODE_CONFIG_H_ */ diff --git a/examples/projects/product/custom_gate/src/custom_json_conversion.c b/examples/projects/product/custom_gate/src/custom_json_conversion.c index dce3b73a5..f94697004 100644 --- a/examples/projects/product/custom_gate/src/custom_json_conversion.c +++ b/examples/projects/product/custom_gate/src/custom_json_conversion.c @@ -75,6 +75,14 @@ void Convert_CustomJsonToMsg(service_t *service, uint16_t target_id, char *prope Luos_SendMsg(service, &msg); return; } + if (property && !strcmp(property, "sampling_freq")) + { + float freq = (float)json_getReal(jobj); + time_luos_t period = TimeOD_TimeFrom_s(1.0f / freq); + TimeOD_TimeToMsg(&period, &msg); + Luos_SendMsg(service, &msg); + return; + } } // This function is called by the gate to convert a message into a piece of Json. diff --git a/examples/projects/product/galvo_demo.gif b/examples/projects/product/galvo_demo.gif new file mode 100644 index 000000000..ebe2cfc50 Binary files /dev/null and b/examples/projects/product/galvo_demo.gif differ diff --git a/examples/projects/product/laser/include/gpio.h b/examples/projects/product/laser/include/gpio.h new file mode 100644 index 000000000..f57136410 --- /dev/null +++ b/examples/projects/product/laser/include/gpio.h @@ -0,0 +1,50 @@ +/** + ****************************************************************************** + * @file gpio.h + * @brief This file contains all the function prototypes for + * the gpio.c file + ****************************************************************************** + * @attention + * + *

© Copyright (c) 2021 STMicroelectronics. + * All rights reserved.

+ * + * This software component is licensed by ST under BSD 3-Clause license, + * the "License"; You may not use this file except in compliance with the + * License. You may obtain a copy of the License at: + * opensource.org/licenses/BSD-3-Clause + * + ****************************************************************************** + */ +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __GPIO_H__ +#define __GPIO_H__ + +#ifdef __cplusplus +extern "C" +{ +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "main.h" + + /* USER CODE BEGIN Includes */ + + /* USER CODE END Includes */ + + /* USER CODE BEGIN Private defines */ + + /* USER CODE END Private defines */ + + void MX_GPIO_Init(void); + + /* USER CODE BEGIN Prototypes */ + + /* USER CODE END Prototypes */ + +#ifdef __cplusplus +} +#endif +#endif /*__ GPIO_H__ */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/examples/projects/product/laser/include/main.h b/examples/projects/product/laser/include/main.h new file mode 100644 index 000000000..677d953e4 --- /dev/null +++ b/examples/projects/product/laser/include/main.h @@ -0,0 +1,76 @@ +/* USER CODE BEGIN Header */ +/** + ****************************************************************************** + * @file : main.h + * @brief : Header for main.c file. + * This file contains the common defines of the application. + ****************************************************************************** + * @attention + * + *

© Copyright (c) 2021 STMicroelectronics. + * All rights reserved.

+ * + * This software component is licensed by ST under BSD 3-Clause license, + * the "License"; You may not use this file except in compliance with the + * License. You may obtain a copy of the License at: + * opensource.org/licenses/BSD-3-Clause + * + ****************************************************************************** + */ +/* USER CODE END Header */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __MAIN_H +#define __MAIN_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l4xx_hal.h" + + /* Private includes ----------------------------------------------------------*/ + /* USER CODE BEGIN Includes */ + + /* USER CODE END Includes */ + + /* Exported types ------------------------------------------------------------*/ + /* USER CODE BEGIN ET */ + + /* USER CODE END ET */ + + /* Exported constants --------------------------------------------------------*/ + /* USER CODE BEGIN EC */ + + /* USER CODE END EC */ + + /* Exported macro ------------------------------------------------------------*/ + /* USER CODE BEGIN EM */ + + /* USER CODE END EM */ + + /* Exported functions prototypes ---------------------------------------------*/ + void Error_Handler(void); + +/* USER CODE BEGIN EFP */ + +/* USER CODE END EFP */ + +/* Private defines -----------------------------------------------------------*/ +#define BTN_Pin GPIO_PIN_11 +#define BTN_GPIO_Port GPIOA +#define LED_Pin GPIO_PIN_3 +#define LED_GPIO_Port GPIOB + /* USER CODE BEGIN Private defines */ + + /* USER CODE END Private defines */ + +#ifdef __cplusplus +} +#endif + +#endif /* __MAIN_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/examples/projects/product/laser/include/stm32l4xx_hal_conf.h b/examples/projects/product/laser/include/stm32l4xx_hal_conf.h new file mode 100644 index 000000000..444e61449 --- /dev/null +++ b/examples/projects/product/laser/include/stm32l4xx_hal_conf.h @@ -0,0 +1,484 @@ +/** + ****************************************************************************** + * @file stm32l4xx_hal_conf.h + * @author MCD Application Team + * @brief HAL configuration template file. + * This file should be copied to the application folder and renamed + * to stm32l4xx_hal_conf.h. + ****************************************************************************** + * @attention + * + *

© Copyright (c) 2017 STMicroelectronics. + * All rights reserved.

+ * + * This software component is licensed by ST under BSD 3-Clause license, + * the "License"; You may not use this file except in compliance with the + * License. You may obtain a copy of the License at: + * opensource.org/licenses/BSD-3-Clause + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef STM32L4xx_HAL_CONF_H +#define STM32L4xx_HAL_CONF_H + +#ifdef __cplusplus +extern "C" +{ +#endif + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ + +/* ########################## Module Selection ############################## */ +/** + * @brief This is the list of modules to be used in the HAL driver + */ +#define HAL_MODULE_ENABLED +/*#define HAL_ADC_MODULE_ENABLED */ +/*#define HAL_CRYP_MODULE_ENABLED */ +/*#define HAL_CAN_MODULE_ENABLED */ +/*#define HAL_COMP_MODULE_ENABLED */ +/*#define HAL_CRYP_MODULE_ENABLED */ +/*#define HAL_DAC_MODULE_ENABLED */ +/*#define HAL_DCMI_MODULE_ENABLED */ +/*#define HAL_DMA2D_MODULE_ENABLED */ +/*#define HAL_DFSDM_MODULE_ENABLED */ +/*#define HAL_DSI_MODULE_ENABLED */ +/*#define HAL_FIREWALL_MODULE_ENABLED */ +/*#define HAL_GFXMMU_MODULE_ENABLED */ +/*#define HAL_HCD_MODULE_ENABLED */ +/*#define HAL_HASH_MODULE_ENABLED */ +/*#define HAL_I2S_MODULE_ENABLED */ +/*#define HAL_IRDA_MODULE_ENABLED */ +/*#define HAL_IWDG_MODULE_ENABLED */ +/*#define HAL_LTDC_MODULE_ENABLED */ +/*#define HAL_LCD_MODULE_ENABLED */ +/*#define HAL_LPTIM_MODULE_ENABLED */ +/*#define HAL_MMC_MODULE_ENABLED */ +/*#define HAL_NAND_MODULE_ENABLED */ +/*#define HAL_NOR_MODULE_ENABLED */ +/*#define HAL_OPAMP_MODULE_ENABLED */ +/*#define HAL_OSPI_MODULE_ENABLED */ +/*#define HAL_OSPI_MODULE_ENABLED */ +/*#define HAL_PCD_MODULE_ENABLED */ +/*#define HAL_PKA_MODULE_ENABLED */ +/*#define HAL_QSPI_MODULE_ENABLED */ +/*#define HAL_QSPI_MODULE_ENABLED */ +/*#define HAL_RNG_MODULE_ENABLED */ +/*#define HAL_RTC_MODULE_ENABLED */ +/*#define HAL_SAI_MODULE_ENABLED */ +/*#define HAL_SD_MODULE_ENABLED */ +/*#define HAL_SMBUS_MODULE_ENABLED */ +/*#define HAL_SMARTCARD_MODULE_ENABLED */ +/*#define HAL_SPI_MODULE_ENABLED */ +/*#define HAL_SRAM_MODULE_ENABLED */ +/*#define HAL_SWPMI_MODULE_ENABLED */ +/*#define HAL_TSC_MODULE_ENABLED */ +/*#define HAL_WWDG_MODULE_ENABLED */ +/*#define HAL_EXTI_MODULE_ENABLED */ +/*#define HAL_PSSI_MODULE_ENABLED */ +#define HAL_GPIO_MODULE_ENABLED +#define HAL_EXTI_MODULE_ENABLED +#define HAL_I2C_MODULE_ENABLED +#define HAL_DMA_MODULE_ENABLED +#define HAL_RCC_MODULE_ENABLED +#define HAL_FLASH_MODULE_ENABLED +#define HAL_PWR_MODULE_ENABLED +#define HAL_CORTEX_MODULE_ENABLED +#define HAL_CRC_MODULE_ENABLED +#define HAL_UART_MODULE_ENABLED +#define HAL_USART_MODULE_ENABLED +#define HAL_TIM_MODULE_ENABLED + +/* ########################## Oscillator Values adaptation ####################*/ +/** + * @brief Adjust the value of External High Speed oscillator (HSE) used in your application. + * This value is used by the RCC HAL module to compute the system frequency + * (when HSE is used as system clock source, directly or through the PLL). + */ +#if !defined(HSE_VALUE) +#define HSE_VALUE ((uint32_t)8000000U) /*!< Value of the External oscillator in Hz */ +#endif /* HSE_VALUE */ + +#if !defined(HSE_STARTUP_TIMEOUT) +#define HSE_STARTUP_TIMEOUT ((uint32_t)100U) /*!< Time out for HSE start up, in ms */ +#endif /* HSE_STARTUP_TIMEOUT */ + +/** + * @brief Internal Multiple Speed oscillator (MSI) default value. + * This value is the default MSI range value after Reset. + */ +#if !defined(MSI_VALUE) +#define MSI_VALUE ((uint32_t)4000000U) /*!< Value of the Internal oscillator in Hz*/ +#endif /* MSI_VALUE */ +/** + * @brief Internal High Speed oscillator (HSI) value. + * This value is used by the RCC HAL module to compute the system frequency + * (when HSI is used as system clock source, directly or through the PLL). + */ +#if !defined(HSI_VALUE) +#define HSI_VALUE ((uint32_t)16000000U) /*!< Value of the Internal oscillator in Hz*/ +#endif /* HSI_VALUE */ + +/** + * @brief Internal High Speed oscillator (HSI48) value for USB FS, SDMMC and RNG. + * This internal oscillator is mainly dedicated to provide a high precision clock to + * the USB peripheral by means of a special Clock Recovery System (CRS) circuitry. + * When the CRS is not used, the HSI48 RC oscillator runs on it default frequency + * which is subject to manufacturing process variations. + */ +#if !defined(HSI48_VALUE) +#define HSI48_VALUE ((uint32_t)48000000U) /*!< Value of the Internal High Speed oscillator for USB FS/SDMMC/RNG in Hz. \ + The real value my vary depending on manufacturing process variations.*/ +#endif /* HSI48_VALUE */ + +/** + * @brief Internal Low Speed oscillator (LSI) value. + */ +#if !defined(LSI_VALUE) +#define LSI_VALUE 32000U /*!< LSI Typical Value in Hz*/ +#endif /* LSI_VALUE */ /*!< Value of the Internal Low Speed oscillator in Hz \ + The real value may vary depending on the variations \ + in voltage and temperature.*/ + +/** + * @brief External Low Speed oscillator (LSE) value. + * This value is used by the UART, RTC HAL module to compute the system frequency + */ +#if !defined(LSE_VALUE) +#define LSE_VALUE 32768U /*!< Value of the External oscillator in Hz*/ +#endif /* LSE_VALUE */ + +#if !defined(LSE_STARTUP_TIMEOUT) +#define LSE_STARTUP_TIMEOUT 5000U /*!< Time out for LSE start up, in ms */ +#endif /* HSE_STARTUP_TIMEOUT */ + +/** + * @brief External clock source for SAI1 peripheral + * This value is used by the RCC HAL module to compute the SAI1 & SAI2 clock source + * frequency. + */ +#if !defined(EXTERNAL_SAI1_CLOCK_VALUE) +#define EXTERNAL_SAI1_CLOCK_VALUE 2097000U /*!< Value of the SAI1 External clock source in Hz*/ +#endif /* EXTERNAL_SAI1_CLOCK_VALUE */ + +/** + * @brief External clock source for SAI2 peripheral + * This value is used by the RCC HAL module to compute the SAI1 & SAI2 clock source + * frequency. + */ +#if !defined(EXTERNAL_SAI2_CLOCK_VALUE) +#define EXTERNAL_SAI2_CLOCK_VALUE 48000U /*!< Value of the SAI2 External clock source in Hz*/ +#endif /* EXTERNAL_SAI2_CLOCK_VALUE */ + + /* Tip: To avoid modifying this file each time you need to use different HSE, + === you can define the HSE value in your toolchain compiler preprocessor. */ + + /* ########################### System Configuration ######################### */ + /** + * @brief This is the HAL system configuration section + */ + +#define VDD_VALUE 3300U /*!< Value of VDD in mv */ +#define TICK_INT_PRIORITY 0U /*!< tick interrupt priority */ +#define USE_RTOS 0U +#define PREFETCH_ENABLE 0U +#define INSTRUCTION_CACHE_ENABLE 1U +#define DATA_CACHE_ENABLE 1U + +/* ########################## Assert Selection ############################## */ +/** + * @brief Uncomment the line below to expanse the "assert_param" macro in the + * HAL drivers code + */ +/* #define USE_FULL_ASSERT 1U */ + +/* ################## Register callback feature configuration ############### */ +/** + * @brief Set below the peripheral configuration to "1U" to add the support + * of HAL callback registration/deregistration feature for the HAL + * driver(s). This allows user application to provide specific callback + * functions thanks to HAL_PPP_RegisterCallback() rather than overwriting + * the default weak callback functions (see each stm32l4xx_hal_ppp.h file + * for possible callback identifiers defined in HAL_PPP_CallbackIDTypeDef + * for each PPP peripheral). + */ +#define USE_HAL_ADC_REGISTER_CALLBACKS 0U +#define USE_HAL_CAN_REGISTER_CALLBACKS 0U +#define USE_HAL_COMP_REGISTER_CALLBACKS 0U +#define USE_HAL_CRYP_REGISTER_CALLBACKS 0U +#define USE_HAL_DAC_REGISTER_CALLBACKS 0U +#define USE_HAL_DCMI_REGISTER_CALLBACKS 0U +#define USE_HAL_DFSDM_REGISTER_CALLBACKS 0U +#define USE_HAL_DMA2D_REGISTER_CALLBACKS 0U +#define USE_HAL_DSI_REGISTER_CALLBACKS 0U +#define USE_HAL_GFXMMU_REGISTER_CALLBACKS 0U +#define USE_HAL_HASH_REGISTER_CALLBACKS 0U +#define USE_HAL_HCD_REGISTER_CALLBACKS 0U +#define USE_HAL_I2C_REGISTER_CALLBACKS 0U +#define USE_HAL_IRDA_REGISTER_CALLBACKS 0U +#define USE_HAL_LPTIM_REGISTER_CALLBACKS 0U +#define USE_HAL_LTDC_REGISTER_CALLBACKS 0U +#define USE_HAL_MMC_REGISTER_CALLBACKS 0U +#define USE_HAL_OPAMP_REGISTER_CALLBACKS 0U +#define USE_HAL_OSPI_REGISTER_CALLBACKS 0U +#define USE_HAL_PCD_REGISTER_CALLBACKS 0U +#define USE_HAL_QSPI_REGISTER_CALLBACKS 0U +#define USE_HAL_RNG_REGISTER_CALLBACKS 0U +#define USE_HAL_RTC_REGISTER_CALLBACKS 0U +#define USE_HAL_SAI_REGISTER_CALLBACKS 0U +#define USE_HAL_SD_REGISTER_CALLBACKS 0U +#define USE_HAL_SMARTCARD_REGISTER_CALLBACKS 0U +#define USE_HAL_SMBUS_REGISTER_CALLBACKS 0U +#define USE_HAL_SPI_REGISTER_CALLBACKS 0U +#define USE_HAL_SWPMI_REGISTER_CALLBACKS 0U +#define USE_HAL_TIM_REGISTER_CALLBACKS 0U +#define USE_HAL_TSC_REGISTER_CALLBACKS 0U +#define USE_HAL_UART_REGISTER_CALLBACKS 0U +#define USE_HAL_USART_REGISTER_CALLBACKS 0U +#define USE_HAL_WWDG_REGISTER_CALLBACKS 0U + + /* ################## SPI peripheral configuration ########################## */ + + /* CRC FEATURE: Use to activate CRC feature inside HAL SPI Driver + * Activated: CRC code is present inside driver + * Deactivated: CRC code cleaned from driver + */ + +#define USE_SPI_CRC 0U + + /* Includes ------------------------------------------------------------------*/ + /** + * @brief Include module's header file + */ + +#ifdef HAL_RCC_MODULE_ENABLED +#include "stm32l4xx_hal_rcc.h" +#endif /* HAL_RCC_MODULE_ENABLED */ + +#ifdef HAL_GPIO_MODULE_ENABLED +#include "stm32l4xx_hal_gpio.h" +#endif /* HAL_GPIO_MODULE_ENABLED */ + +#ifdef HAL_DMA_MODULE_ENABLED +#include "stm32l4xx_hal_dma.h" +#endif /* HAL_DMA_MODULE_ENABLED */ + +#ifdef HAL_DFSDM_MODULE_ENABLED +#include "stm32l4xx_hal_dfsdm.h" +#endif /* HAL_DFSDM_MODULE_ENABLED */ + +#ifdef HAL_CORTEX_MODULE_ENABLED +#include "stm32l4xx_hal_cortex.h" +#endif /* HAL_CORTEX_MODULE_ENABLED */ + +#ifdef HAL_ADC_MODULE_ENABLED +#include "stm32l4xx_hal_adc.h" +#endif /* HAL_ADC_MODULE_ENABLED */ + +#ifdef HAL_CAN_MODULE_ENABLED +#include "stm32l4xx_hal_can.h" +#endif /* HAL_CAN_MODULE_ENABLED */ + +#ifdef HAL_CAN_LEGACY_MODULE_ENABLED +#include "Legacy/stm32l4xx_hal_can_legacy.h" +#endif /* HAL_CAN_LEGACY_MODULE_ENABLED */ + +#ifdef HAL_COMP_MODULE_ENABLED +#include "stm32l4xx_hal_comp.h" +#endif /* HAL_COMP_MODULE_ENABLED */ + +#ifdef HAL_CRC_MODULE_ENABLED +#include "stm32l4xx_hal_crc.h" +#endif /* HAL_CRC_MODULE_ENABLED */ + +#ifdef HAL_CRYP_MODULE_ENABLED +#include "stm32l4xx_hal_cryp.h" +#endif /* HAL_CRYP_MODULE_ENABLED */ + +#ifdef HAL_DAC_MODULE_ENABLED +#include "stm32l4xx_hal_dac.h" +#endif /* HAL_DAC_MODULE_ENABLED */ + +#ifdef HAL_DCMI_MODULE_ENABLED +#include "stm32l4xx_hal_dcmi.h" +#endif /* HAL_DCMI_MODULE_ENABLED */ + +#ifdef HAL_DMA2D_MODULE_ENABLED +#include "stm32l4xx_hal_dma2d.h" +#endif /* HAL_DMA2D_MODULE_ENABLED */ + +#ifdef HAL_DSI_MODULE_ENABLED +#include "stm32l4xx_hal_dsi.h" +#endif /* HAL_DSI_MODULE_ENABLED */ + +#ifdef HAL_EXTI_MODULE_ENABLED +#include "stm32l4xx_hal_exti.h" +#endif /* HAL_EXTI_MODULE_ENABLED */ + +#ifdef HAL_GFXMMU_MODULE_ENABLED +#include "stm32l4xx_hal_gfxmmu.h" +#endif /* HAL_GFXMMU_MODULE_ENABLED */ + +#ifdef HAL_FIREWALL_MODULE_ENABLED +#include "stm32l4xx_hal_firewall.h" +#endif /* HAL_FIREWALL_MODULE_ENABLED */ + +#ifdef HAL_FLASH_MODULE_ENABLED +#include "stm32l4xx_hal_flash.h" +#endif /* HAL_FLASH_MODULE_ENABLED */ + +#ifdef HAL_HASH_MODULE_ENABLED +#include "stm32l4xx_hal_hash.h" +#endif /* HAL_HASH_MODULE_ENABLED */ + +#ifdef HAL_HCD_MODULE_ENABLED +#include "stm32l4xx_hal_hcd.h" +#endif /* HAL_HCD_MODULE_ENABLED */ + +#ifdef HAL_I2C_MODULE_ENABLED +#include "stm32l4xx_hal_i2c.h" +#endif /* HAL_I2C_MODULE_ENABLED */ + +#ifdef HAL_IRDA_MODULE_ENABLED +#include "stm32l4xx_hal_irda.h" +#endif /* HAL_IRDA_MODULE_ENABLED */ + +#ifdef HAL_IWDG_MODULE_ENABLED +#include "stm32l4xx_hal_iwdg.h" +#endif /* HAL_IWDG_MODULE_ENABLED */ + +#ifdef HAL_LCD_MODULE_ENABLED +#include "stm32l4xx_hal_lcd.h" +#endif /* HAL_LCD_MODULE_ENABLED */ + +#ifdef HAL_LPTIM_MODULE_ENABLED +#include "stm32l4xx_hal_lptim.h" +#endif /* HAL_LPTIM_MODULE_ENABLED */ + +#ifdef HAL_LTDC_MODULE_ENABLED +#include "stm32l4xx_hal_ltdc.h" +#endif /* HAL_LTDC_MODULE_ENABLED */ + +#ifdef HAL_MMC_MODULE_ENABLED +#include "stm32l4xx_hal_mmc.h" +#endif /* HAL_MMC_MODULE_ENABLED */ + +#ifdef HAL_NAND_MODULE_ENABLED +#include "stm32l4xx_hal_nand.h" +#endif /* HAL_NAND_MODULE_ENABLED */ + +#ifdef HAL_NOR_MODULE_ENABLED +#include "stm32l4xx_hal_nor.h" +#endif /* HAL_NOR_MODULE_ENABLED */ + +#ifdef HAL_OPAMP_MODULE_ENABLED +#include "stm32l4xx_hal_opamp.h" +#endif /* HAL_OPAMP_MODULE_ENABLED */ + +#ifdef HAL_OSPI_MODULE_ENABLED +#include "stm32l4xx_hal_ospi.h" +#endif /* HAL_OSPI_MODULE_ENABLED */ + +#ifdef HAL_PCD_MODULE_ENABLED +#include "stm32l4xx_hal_pcd.h" +#endif /* HAL_PCD_MODULE_ENABLED */ + +#ifdef HAL_PKA_MODULE_ENABLED +#include "stm32l4xx_hal_pka.h" +#endif /* HAL_PKA_MODULE_ENABLED */ + +#ifdef HAL_PSSI_MODULE_ENABLED +#include "stm32l4xx_hal_pssi.h" +#endif /* HAL_PSSI_MODULE_ENABLED */ + +#ifdef HAL_PWR_MODULE_ENABLED +#include "stm32l4xx_hal_pwr.h" +#endif /* HAL_PWR_MODULE_ENABLED */ + +#ifdef HAL_QSPI_MODULE_ENABLED +#include "stm32l4xx_hal_qspi.h" +#endif /* HAL_QSPI_MODULE_ENABLED */ + +#ifdef HAL_RNG_MODULE_ENABLED +#include "stm32l4xx_hal_rng.h" +#endif /* HAL_RNG_MODULE_ENABLED */ + +#ifdef HAL_RTC_MODULE_ENABLED +#include "stm32l4xx_hal_rtc.h" +#endif /* HAL_RTC_MODULE_ENABLED */ + +#ifdef HAL_SAI_MODULE_ENABLED +#include "stm32l4xx_hal_sai.h" +#endif /* HAL_SAI_MODULE_ENABLED */ + +#ifdef HAL_SD_MODULE_ENABLED +#include "stm32l4xx_hal_sd.h" +#endif /* HAL_SD_MODULE_ENABLED */ + +#ifdef HAL_SMARTCARD_MODULE_ENABLED +#include "stm32l4xx_hal_smartcard.h" +#endif /* HAL_SMARTCARD_MODULE_ENABLED */ + +#ifdef HAL_SMBUS_MODULE_ENABLED +#include "stm32l4xx_hal_smbus.h" +#endif /* HAL_SMBUS_MODULE_ENABLED */ + +#ifdef HAL_SPI_MODULE_ENABLED +#include "stm32l4xx_hal_spi.h" +#endif /* HAL_SPI_MODULE_ENABLED */ + +#ifdef HAL_SRAM_MODULE_ENABLED +#include "stm32l4xx_hal_sram.h" +#endif /* HAL_SRAM_MODULE_ENABLED */ + +#ifdef HAL_SWPMI_MODULE_ENABLED +#include "stm32l4xx_hal_swpmi.h" +#endif /* HAL_SWPMI_MODULE_ENABLED */ + +#ifdef HAL_TIM_MODULE_ENABLED +#include "stm32l4xx_hal_tim.h" +#endif /* HAL_TIM_MODULE_ENABLED */ + +#ifdef HAL_TSC_MODULE_ENABLED +#include "stm32l4xx_hal_tsc.h" +#endif /* HAL_TSC_MODULE_ENABLED */ + +#ifdef HAL_UART_MODULE_ENABLED +#include "stm32l4xx_hal_uart.h" +#endif /* HAL_UART_MODULE_ENABLED */ + +#ifdef HAL_USART_MODULE_ENABLED +#include "stm32l4xx_hal_usart.h" +#endif /* HAL_USART_MODULE_ENABLED */ + +#ifdef HAL_WWDG_MODULE_ENABLED +#include "stm32l4xx_hal_wwdg.h" +#endif /* HAL_WWDG_MODULE_ENABLED */ + +/* Exported macro ------------------------------------------------------------*/ +#ifdef USE_FULL_ASSERT + /** + * @brief The assert_param macro is used for function's parameters check. + * @param expr If expr is false, it calls assert_failed function + * which reports the name of the source file and the source + * line number of the call that failed. + * If expr is true, it returns no value. + * @retval None + */ +#define assert_param(expr) ((expr) ? (void)0U : assert_failed((uint8_t *)__FILE__, __LINE__)) + /* Exported functions ------------------------------------------------------- */ + void assert_failed(uint8_t *file, uint32_t line); +#else +#define assert_param(expr) ((void)0U) +#endif /* USE_FULL_ASSERT */ + +#ifdef __cplusplus +} +#endif + +#endif /* STM32L4xx_HAL_CONF_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/examples/projects/product/laser/include/stm32l4xx_it.h b/examples/projects/product/laser/include/stm32l4xx_it.h new file mode 100644 index 000000000..ace6ff14c --- /dev/null +++ b/examples/projects/product/laser/include/stm32l4xx_it.h @@ -0,0 +1,71 @@ +/* USER CODE BEGIN Header */ +/** + ****************************************************************************** + * @file stm32l4xx_it.h + * @brief This file contains the headers of the interrupt handlers. + ****************************************************************************** + * @attention + * + *

© Copyright (c) 2021 STMicroelectronics. + * All rights reserved.

+ * + * This software component is licensed by ST under BSD 3-Clause license, + * the "License"; You may not use this file except in compliance with the + * License. You may obtain a copy of the License at: + * opensource.org/licenses/BSD-3-Clause + * + ****************************************************************************** + */ +/* USER CODE END Header */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L4xx_IT_H + #define __STM32L4xx_IT_H + + #ifdef __cplusplus +extern "C" +{ + #endif + + /* Private includes ----------------------------------------------------------*/ + /* USER CODE BEGIN Includes */ + + /* USER CODE END Includes */ + + /* Exported types ------------------------------------------------------------*/ + /* USER CODE BEGIN ET */ + + /* USER CODE END ET */ + + /* Exported constants --------------------------------------------------------*/ + /* USER CODE BEGIN EC */ + + /* USER CODE END EC */ + + /* Exported macro ------------------------------------------------------------*/ + /* USER CODE BEGIN EM */ + + /* USER CODE END EM */ + + /* Exported functions prototypes ---------------------------------------------*/ + void NMI_Handler(void); + void HardFault_Handler(void); + void MemManage_Handler(void); + void BusFault_Handler(void); + void UsageFault_Handler(void); + void SVC_Handler(void); + void DebugMon_Handler(void); + void PendSV_Handler(void); + void SysTick_Handler(void); + void DMA1_Channel3_IRQHandler(void); + /* USER CODE BEGIN EFP */ + + /* USER CODE END EFP */ + + #ifdef __cplusplus +} + #endif + +#endif /* __STM32L4xx_IT_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/examples/projects/product/laser/lib/Galvo/README.md b/examples/projects/product/laser/lib/Galvo/README.md new file mode 100644 index 000000000..d447e5362 --- /dev/null +++ b/examples/projects/product/laser/lib/Galvo/README.md @@ -0,0 +1,21 @@ +Luos logo + +![](https://github.com/Luos-io/luos_engine/actions/workflows/build.yml/badge.svg) +[![](https://img.shields.io/github/license/Luos-io/luos_engine)](https://github.com/Luos-io/luos_engine/blob/master/LICENSE) + +[![](https://img.shields.io/badge/Luos-Documentation-34A3B4)](https://www.luos.io/docs/) +[![PlatformIO Registry](https://badges.registry.platformio.org/packages/luos/library/luos_engine.svg)](https://registry.platformio.org/libraries/luos_engine/luos_engine) + +[![](https://img.shields.io/discord/902486791658041364?label=Discord&logo=discord&style=social)](http://bit.ly/JoinLuosDiscord) +[![](https://img.shields.io/badge/LinkedIn-Share-0077B5?style=social&logo=linkedin)](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fgithub.com%2Fluos-io) + +# Galvo driver using XY2-100 protocol + +Driver for using a laser galvo using XY2-100 protocol in your projects with Luos. + +# Linked project + +This driver is linked to the [Galvo project](../../Projects/NUCLEO_L476RG/laser). + +[![](https://img.shields.io/badge/Luos-Documentation-34A3B4)](https://www.luos.io) +[![](https://img.shields.io/badge/LinkedIn-Follow%20us-0077B5?style=flat&logo=linkedin)](https://www.linkedin.com/company/luos) diff --git a/examples/projects/product/laser/lib/Galvo/galvo.c b/examples/projects/product/laser/lib/Galvo/galvo.c new file mode 100644 index 000000000..d7c5d013b --- /dev/null +++ b/examples/projects/product/laser/lib/Galvo/galvo.c @@ -0,0 +1,131 @@ +/****************************************************************************** + * @file galvo + * @brief driver example a laser galvo + * @author Luos + * @version 0.0.0 + ******************************************************************************/ +#include "galvo.h" +#include "xy2-100.h" + +/******************************************************************************* + * Definitions + ******************************************************************************/ +pos_2d_t stream_buf[4096]; +streaming_channel_t stream; +time_luos_t period; +control_t control; +buffer_mode_t buffer_mode = SINGLE; + +/******************************************************************************* + * Variables + ******************************************************************************/ + +/******************************************************************************* + * Function + ******************************************************************************/ +static void Galvo_MsgHandler(service_t *service, const msg_t *msg); + +/****************************************************************************** + * @brief init must be call in project init + * @param None + * @return None + ******************************************************************************/ +void Galvo_Init(void) +{ + Xy_Init(); + + revision_t revision = {.major = 1, .minor = 0, .build = 0}; + Luos_CreateService(Galvo_MsgHandler, POINT_2D, "galvo", revision); + stream = Streaming_CreateChannel(stream_buf, sizeof(stream_buf), 2 * sizeof(uint16_t)); + period = TimeOD_TimeFrom_s(1.0 / 10000.0); // Configure the trajectory samplerate at 100Hz + control.flux = STOP; +} + +/****************************************************************************** + * @brief loop must be call in project loop + * @param None + * @return None + ******************************************************************************/ +void Galvo_Loop(void) +{ +} + +/****************************************************************************** + * @brief Msg Handler call back when a msg receive for this service + * @param Service destination + * @param Msg receive + * @return None + ******************************************************************************/ +static void Galvo_MsgHandler(service_t *service, const msg_t *msg) +{ + if (msg->header.cmd == GET_CMD) + { + // The galvo don't send anything back + return; + } + if (msg->header.cmd == CONTROL) + { + // Get the control value + ControlOD_ControlFromMsg(&control, msg); + if (control.flux == PLAY) + { + // Start the trajectory + Xy_Start(&stream, period); + } + else + { + // Stop the trajectory + Xy_Stop(); + } + } + if (msg->header.cmd == LINEAR_POSITION_2D) + { + if (buffer_mode == STREAM) + { + // The galvo is in single mode, we can consider it as a streaming of point that will be consumed by the galvo + Luos_ReceiveStreaming(service, msg, &stream); + } + if (buffer_mode == CONTINUOUS) + { + // The galvo is in CONTINUOUS, The buffer need to be loaded with the trajectory and the galvo will play it in loop. + volatile int size = Luos_ReceiveData(service, msg, (uint8_t *)&stream_buf); + if (size > 0) + { + LUOS_ASSERT(size <= sizeof(stream_buf)); + // overwrite the streaming structure to manage the bufferin loop + // set the write pointer in the end of the data + stream.data_ptr = stream_buf + size / stream.data_size; + if (stream.data_ptr < stream.sample_ptr) + { + // If the read pointer overlap the write pointer point it back to the begining of the buffer + // set the read pointer at the begining of the data + stream.sample_ptr = stream_buf; + } + } + } + else + { + // The galvo is in SINGLE, The buffer need to be loaded with the trajectory and the galvo will play it from the begining of the buffer to the end. + volatile int size = Luos_ReceiveData(service, msg, (uint8_t *)&stream_buf); + if (size > 0) + { + LUOS_ASSERT(size <= sizeof(stream_buf)); + // overwrite the streaming structure to manage the bufferin loop + // set the write pointer in the end of the data + stream.data_ptr = stream_buf + size / stream.data_size; + // set the read pointer at the begining of the data + stream.sample_ptr = stream_buf; + } + } + } + if (msg->header.cmd == BUFFER_MODE) + { + buffer_mode = msg->data[0]; + Xy_BufferMode(buffer_mode); + } + if (msg->header.cmd == TIME) + { + // Get the time + TimeOD_TimeFromMsg(&period, msg); + } +} diff --git a/examples/projects/product/laser/lib/Galvo/galvo.h b/examples/projects/product/laser/lib/Galvo/galvo.h new file mode 100644 index 000000000..6a7a3f421 --- /dev/null +++ b/examples/projects/product/laser/lib/Galvo/galvo.h @@ -0,0 +1,25 @@ +/****************************************************************************** + * @file galvo + * @brief driver example a simple button + * @author Luos + * @version 0.0.0 + ******************************************************************************/ +#ifndef GALVO_H +#define GALVO_H + +#include "luos_engine.h" +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/******************************************************************************* + * Variables + ******************************************************************************/ + +/******************************************************************************* + * Function + ******************************************************************************/ +void Galvo_Init(void); +void Galvo_Loop(void); + +#endif /* GALVO_H */ diff --git a/examples/projects/product/laser/lib/Galvo/galvo_config.h b/examples/projects/product/laser/lib/Galvo/galvo_config.h new file mode 100644 index 000000000..2db89c415 --- /dev/null +++ b/examples/projects/product/laser/lib/Galvo/galvo_config.h @@ -0,0 +1,97 @@ +/****************************************************************************** + * @file galvo_config.h + * @brief Galvo configuration + * @MCU Family STM32L4 + * @author Luos + * @version 0.0.0 + ******************************************************************************/ +#ifndef _GALVO_HAL_CONFIG_H_ +#define _GALVO_HAL_CONFIG_H_ + +#ifndef MCUFREQ + #define MCUFREQ 80000000 // MCU frequence +#endif + +// ********************* GPIO ********************* +// Galvo need all the pins (except enable) to be on the same port +#ifndef GALVO_PORT + #define GALVO_PORT GPIOC +#endif + +#ifndef GALVO_PIN_CLOCK_ENABLE + #define GALVO_PIN_CLOCK_ENABLE() \ + do \ + { \ + __HAL_RCC_GPIOC_CLK_ENABLE(); \ + } while (0U) +#endif + +// CLOCK Pinout +#ifndef GALVO_CLOCK_PIN + #define GALVO_CLOCK_PIN GPIO_PIN_0 +#endif + +// SYNC Pinout +#ifndef GALVO_SYNC_PIN + #define GALVO_SYNC_PIN GPIO_PIN_1 +#endif + +// X Pinout +#ifndef GALVO_X_PIN + #define GALVO_X_PIN GPIO_PIN_2 +#endif + +// Y Pinout +#ifndef GALVO_Y_PIN + #define GALVO_Y_PIN GPIO_PIN_3 +#endif + +// ENABLE Pinout +#ifndef GALVO_ENABLE_PIN + #define GALVO_ENABLE_PIN GPIO_PIN_5 +#endif + +// ********************* TIMER ********************* +#ifndef GALVO_TIMER + #define GALVO_TIMER TIM6 +#endif + +#ifndef GALVO_BAUDRATE + #define GALVO_BAUDRATE 2000000 +#endif + +#ifndef GALVO_TIMER_CLOCK_ENABLE + #define GALVO_TIMER_CLOCK_ENABLE() __HAL_RCC_TIM6_CLK_ENABLE() +#endif + +// ********************* DMA ********************* +#ifndef GALVO_DMA_CLOCK_ENABLE + #define GALVO_DMA_CLOCK_ENABLE() __HAL_RCC_DMA1_CLK_ENABLE(); +#endif + +#ifndef GALVO_DMA + #define GALVO_DMA DMA1 +#endif + +#ifndef GALVO_DMA_CHANNEL + #define GALVO_DMA_CHANNEL DMA1_Channel3 +#endif + +#ifndef GALVO_DMA_REQUEST + #define GALVO_DMA_REQUEST DMA_REQUEST_6 +#endif + +#ifndef GALVO_DMA_IRQ + #define GALVO_DMA_IRQ DMA1_Channel3_IRQn +#endif + +#ifndef GALVO_DMA_IRQHANDLER + #define GALVO_DMA_IRQHANDLER() DMA1_Channel3_IRQHandler() +#endif + +// ********************* BUFFER ********************* +#ifndef GALVO_BUFFER_SIZE + #define GALVO_BUFFER_SIZE 8000 // Buffer size need to be a multiple of 40 +#endif + +#endif /* _GALVO_HAL_CONFIG_H_ */ diff --git a/examples/projects/product/laser/lib/Galvo/library.json b/examples/projects/product/laser/lib/Galvo/library.json new file mode 100644 index 000000000..a4a26aa46 --- /dev/null +++ b/examples/projects/product/laser/lib/Galvo/library.json @@ -0,0 +1,14 @@ +{ + "name": "Galvo", + "keywords": "robus,network,microservice,luos,operating system,os,embedded,communication,service,ST", + "description": "a laser galvo driver", + "version": "1.0.0", + "authors": { + "name": "Luos", + "url": "https://luos.io" + }, + "dependencies": { + "luos_engine": "^3.1.0" + }, + "licence": "MIT" +} diff --git a/examples/projects/product/laser/lib/Galvo/xy2-100.c b/examples/projects/product/laser/lib/Galvo/xy2-100.c new file mode 100644 index 000000000..d6cccd3a3 --- /dev/null +++ b/examples/projects/product/laser/lib/Galvo/xy2-100.c @@ -0,0 +1,365 @@ +/****************************************************************************** + * @file xy2-100 + * @brief driver for the xy2-100 protocol + * @author Luos + * @version 0.0.0 + * + * + * This driver allow to drive a xy2-100 protocol (meaning 2bytes X and Y data at 100KHz transmission) + * This driver use a combination of timer + DMA + GPIO port to generate the signal in hardware without MCU intervention. + * This way you can make it run on almost any MCU with these peripherals and still have a very precise signal and plenty of CPU time for other tasks. + * + * The timer is used to generate the clock signal at the right frequency. Each timer overflow generate a trigger to the DMA. At each trigger the DMA send the next byte to the GPIO port. + * DMA generate an interrupt at half transfer and at transfer complete. This allow to manage the older half of buffer while the DMA is sending the new one. The DMA is configured to ring on the buffer to have a continuous flux on information. + * You can increase the buffer size to reduce the number of IRQ and increase the CPU time available for other tasks. + * + * The input of this driver is a sample ring buffer you can feed with data providing a given sampling frequency. This driver will consume the data at the right frequency and linearize the trajectory between the samples. + * You can start pause or stop the trajectory execution at any time. + ******************************************************************************/ + +#include "xy2-100.h" +#include "galvo_config.h" + +#include "stm32l4xx_ll_gpio.h" +#include "stm32l4xx_ll_system.h" +#include "gpio.h" + +/******************************************************************************* + * Definitions + ******************************************************************************/ +typedef struct +{ + uint32_t x; + int32_t incr_x; + uint32_t target_x; + uint32_t y; + int32_t incr_y; + uint32_t target_y; + int32_t point_nbr_to_target; +} xy2_interpolation_t; + +void Xy_TransferCompleteCallback(DMA_HandleTypeDef *hdma); +void Xy_HalfTransferCallback(DMA_HandleTypeDef *hdma); +inline bool Xy_ComputeNextPoints(uint8_t *data); +inline bool Xy_GetNextTrajSample(void); +inline uint8_t Xy_Parity(uint16_t v); +inline uint32_t Xy_BuildMsg(uint16_t data); + +/******************************************************************************* + * Variables + ******************************************************************************/ + +DMA_HandleTypeDef hdma_tim_up; +TIM_HandleTypeDef htim; + +control_t traj_control = {.unmap = 0}; +streaming_channel_t *streaming_channel; +xy2_interpolation_t xy2_interpolation; +uint8_t dma_buff[GALVO_BUFFER_SIZE] = {0}; +volatile time_luos_t sample_period; +buffer_mode_t xy_buffer_mode = SINGLE; +/******************************************************************************* + * Function + ******************************************************************************/ + +// Init the pins timer and DMA peripherals to drive the xy2-100 protocol +void Xy_Init(void) +{ + // Init pins as output GPIO + GALVO_PIN_CLOCK_ENABLE(); + GPIO_InitTypeDef GPIO_InitStruct = {0}; + GPIO_InitStruct.Pin = GALVO_CLOCK_PIN | GALVO_SYNC_PIN | GALVO_X_PIN | GALVO_Y_PIN | GALVO_ENABLE_PIN; + GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; + HAL_GPIO_Init(GALVO_PORT, &GPIO_InitStruct); + + // Init timer + GALVO_TIMER_CLOCK_ENABLE(); + uint32_t timer_count = (MCUFREQ / (GALVO_BAUDRATE * 2)); + TIM_MasterConfigTypeDef sMasterConfig = {0}; + + htim.Instance = GALVO_TIMER; + htim.Init.Prescaler = 0; + htim.Init.CounterMode = TIM_COUNTERMODE_UP; + htim.Init.Period = timer_count - 1; + htim.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_ENABLE; + HAL_TIM_Base_Init(&htim); + sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET; + sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE; + HAL_TIMEx_MasterConfigSynchronization(&htim, &sMasterConfig); + + // Init DMA + GALVO_DMA_CLOCK_ENABLE(); + hdma_tim_up.Instance = GALVO_DMA_CHANNEL; + hdma_tim_up.Init.Request = GALVO_DMA_REQUEST; + hdma_tim_up.Init.Direction = DMA_MEMORY_TO_PERIPH; + hdma_tim_up.Init.PeriphInc = DMA_PINC_DISABLE; + hdma_tim_up.Init.MemInc = DMA_MINC_ENABLE; + hdma_tim_up.Init.PeriphDataAlignment = DMA_PDATAALIGN_BYTE; + hdma_tim_up.Init.MemDataAlignment = DMA_MDATAALIGN_BYTE; + hdma_tim_up.Init.Mode = DMA_CIRCULAR; + hdma_tim_up.Init.Priority = DMA_PRIORITY_LOW; + HAL_DMA_Init(&hdma_tim_up); + + // Enable timer DMA request enable + __HAL_TIM_ENABLE_DMA(&htim, TIM_DMA_UPDATE); + + // Set DMA half transfert callback + HAL_DMA_RegisterCallback(&hdma_tim_up, HAL_DMA_XFER_HALFCPLT_CB_ID, Xy_HalfTransferCallback); + // Set DMA transfert complete callback + HAL_DMA_RegisterCallback(&hdma_tim_up, HAL_DMA_XFER_CPLT_CB_ID, Xy_TransferCompleteCallback); + + // Init DMA interrupt + NVIC_SetPriority(GALVO_DMA_IRQ, 2); + NVIC_EnableIRQ(GALVO_DMA_IRQ); + + // Start timer + HAL_TIM_Base_Start(&htim); + + // Consider the trajectory as stopped + traj_control.flux = STOP; + xy2_interpolation.point_nbr_to_target = 0; +} + +// This callback is raised when the DMA transfert is complete, the last half of the buffer have to be updated with the next points +void Xy_TransferCompleteCallback(DMA_HandleTypeDef *hdma) +{ + static bool traj_end_complete = false; + // Check if the trajectory is finished + if (traj_end_complete == true) + { + // We just played the end of the trajectory, stop the DMA + // Stop DMA + HAL_DMA_Abort_IT(&hdma_tim_up); + // Consider the trajectory as stopped + traj_control.flux = STOP; + traj_end_complete = false; + return; + } + else + { + // Compute the next points and fill the second half of the buffer + traj_end_complete = Xy_ComputeNextPoints(dma_buff + (GALVO_BUFFER_SIZE / 2)); + } +} + +// This callback is raised when the DMA transfert is half complete, the first half of the buffer have to be updated with the next points +void Xy_HalfTransferCallback(DMA_HandleTypeDef *hdma) +{ + static bool traj_end_half = false; + // Check if the trajectory is finished + if (traj_end_half == true) + { + // We just played the end of the trajectory, stop the DMA + // Stop DMA + HAL_DMA_Abort_IT(&hdma_tim_up); + // Consider the trajectory as stopped + traj_control.flux = STOP; + traj_end_half = false; + return; + } + else + { + // Compute the next points and fill the second half of the buffer + traj_end_half = Xy_ComputeNextPoints(dma_buff); + } +} + +// This is the replacement of the DMA IRQ handler provided by ST. If you have your ST code doing this job you can remove this function. +void DMA1_Channel3_IRQHandler() +{ + // You can unable the led and check the pin with an oscilloscope to see the occupation ratio of the galvo on the MCU + // turn the led on + // HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_SET); + // Manage the IRQ + HAL_DMA_IRQHandler(&hdma_tim_up); + // turn the led off + // HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_RESET); +} + +// Start the trajectory with a given buffer at a given sampling frequency +void Xy_Start(streaming_channel_t *stream, time_luos_t period) +{ + // First check if we are already running + if (traj_control.flux == PLAY) + { + // We are already running, just continue + return; + } + streaming_channel = stream; + sample_period = period; + // Compute the first points and fill half of the buffer + Xy_ComputeNextPoints(dma_buff); + // Compute the second points and fill the other half of the buffer + Xy_ComputeNextPoints(dma_buff + (GALVO_BUFFER_SIZE / 2)); + // Start DMA + HAL_DMA_Start_IT(&hdma_tim_up, (uint32_t)dma_buff, (uint32_t)&GALVO_PORT->ODR, GALVO_BUFFER_SIZE); + + // Consider the trajectory as running + traj_control.flux = PLAY; +} + +// Stop the trajectory +void Xy_Stop(void) +{ + // Stop DMA + HAL_DMA_Abort_IT(&hdma_tim_up); + // Disable the galvo + HAL_GPIO_WritePin(GALVO_PORT, GALVO_ENABLE_PIN, GPIO_PIN_RESET); + // Consider the trajectory as stopped + traj_control.flux = STOP; +} + +// Compute the next points and fill half of the buffer +// this function return true if the buffer is filled with the last point. +bool Xy_ComputeNextPoints(uint8_t *data) +{ + // Compute interpolation of points using the last point and the target point + uint32_t clk_tick_nbr = 0; + const uint32_t msg_sync = 0x0FFFFE; + const uint32_t tick_size = (GALVO_BUFFER_SIZE / 2); + volatile uint32_t msg_X; + volatile uint32_t msg_Y; + if (xy2_interpolation.point_nbr_to_target == -1) + { + // We already finished the trajectory fill the buffer with zeros + memset((void *)data, 0, tick_size); + xy2_interpolation.point_nbr_to_target = 0; + // Those are not the last point, this is just void data, return false. + return false; + } + + while (clk_tick_nbr < tick_size) + { + if (xy2_interpolation.point_nbr_to_target == 0) + { + // We need to get a new target point + if (Xy_GetNextTrajSample() == false) + { + // We don't have any new sample to compute, fill the buffer with the last point first time will be enabled, the other ones will not. + // Feel the 40 bytes of the buffer containing the 20 bits of the message. This will allo to stop the DMA with a good value. + // We have to divide the value by 2^16 to get the real value because we use integer instead of float in the xy2_interpolation_t struct to optimize the computation. + msg_X = Xy_BuildMsg((uint16_t)(xy2_interpolation.x >> 16)); + msg_Y = Xy_BuildMsg((uint16_t)(xy2_interpolation.y >> 16)); + for (int i = 0; i < 20; i++) + { + uint8_t sync_bit = (msg_sync >> (19 - i)) & 1; + uint8_t x_bit = (msg_X >> (19 - i)) & 1; + uint8_t y_bit = (msg_Y >> (19 - i)) & 1; + data[clk_tick_nbr + (i * 2)] = GALVO_CLOCK_PIN | (sync_bit * GALVO_SYNC_PIN) | (x_bit * GALVO_X_PIN) | (y_bit * GALVO_Y_PIN) | GALVO_ENABLE_PIN; + // Reverse the GALVO_CLOCK_PIN + data[clk_tick_nbr + (i * 2) + 1] = data[clk_tick_nbr + (i * 2)] & ~GALVO_CLOCK_PIN; + } + clk_tick_nbr += 40; + memset((void *)&data[clk_tick_nbr], 0, tick_size - clk_tick_nbr); + xy2_interpolation.point_nbr_to_target--; + // This part of the buffer contain the last point, return true. + return true; + } + } + // Compute the next point + xy2_interpolation.x = xy2_interpolation.x + xy2_interpolation.incr_x; + xy2_interpolation.y = xy2_interpolation.y + xy2_interpolation.incr_y; + // Decrease the number of point to reach the target + xy2_interpolation.point_nbr_to_target--; + // Create the messages for x and y + // We have to divide the value by 2^16 to get the real value because we use integer instead of float in the xy2_interpolation_t struct to optimize the computation. + msg_X = Xy_BuildMsg((uint16_t)(xy2_interpolation.x >> 16)); + msg_Y = Xy_BuildMsg((uint16_t)(xy2_interpolation.y >> 16)); + // Feel the 40 bytes of the buffer containing the 20 bits of the message + for (int i = 0; i < 20; i++) + { + uint8_t sync_bit = (msg_sync >> (19 - i)) & 1; + uint8_t x_bit = (msg_X >> (19 - i)) & 1; + uint8_t y_bit = (msg_Y >> (19 - i)) & 1; + data[clk_tick_nbr + (i * 2)] = GALVO_CLOCK_PIN | (sync_bit * GALVO_SYNC_PIN) | (x_bit * GALVO_X_PIN) | (y_bit * GALVO_Y_PIN) | GALVO_ENABLE_PIN; + // Reverse the GALVO_CLOCK_PIN + data[clk_tick_nbr + (i * 2) + 1] = data[clk_tick_nbr + (i * 2)] & ~GALVO_CLOCK_PIN; + } + clk_tick_nbr += 40; + } + // This part of the buffer contain normal points, return false. + return false; +} + +// Compute the parity of a 16bits value +uint8_t Xy_Parity(uint16_t v) +{ + uint8_t t = (uint8_t)v ^ v >> 8; + t ^= t >> 4; + t ^= t >> 2; + t ^= t >> 1; + return (t & 1); +} + +// Build a xy2-100 message for one axis +uint32_t Xy_BuildMsg(uint16_t data) +{ + return (1 << 17) | (data << 1) | Xy_Parity(data); +} + +// Get the next sample from the ring buffer and compute dome values to optimize the trajectory interpolation +bool Xy_GetNextTrajSample(void) +{ + // Move the target point as current position + xy2_interpolation.x = xy2_interpolation.target_x; + xy2_interpolation.y = xy2_interpolation.target_y; + // Get the next sample from the ring buffer + uint16_t sample[2]; + if (Streaming_GetAvailableSampleNB(streaming_channel) == 0) + { + // We don't have any new sample to compute + switch (xy_buffer_mode) + { + case SINGLE: + // We are in single mode, we have to loop on the ring buffer + // Put the read pointer at the begining of the buffer + streaming_channel->sample_ptr = streaming_channel->ring_buffer; + return false; + break; + case CONTINUOUS: + // We are in continuous mode, we have to loop on the ring buffer + // Put the read pointer at the begining of the buffer + streaming_channel->sample_ptr = streaming_channel->ring_buffer; + // Get the first sample + if (Streaming_GetAvailableSampleNB(streaming_channel) == 0) + { + // We don't have any new sample to compute + return false; + } + break; + case STREAM: + // We are in stream mode, we have to wait for new data + return false; + break; + default: + LUOS_ASSERT(0); + break; + } + } + Streaming_GetSample(streaming_channel, (void *)sample, 1); + // Convert the sample into a position + // To optimize the computation we use integer instead of float. We have to multiply the values by 2^16 to keep as much precision as possible. + xy2_interpolation.target_x = sample[0] << 16; + xy2_interpolation.target_y = sample[1] << 16; + + // Compute the number of point to reach the target + xy2_interpolation.point_nbr_to_target = ((GALVO_BAUDRATE / 20) / (1 / TimeOD_TimeTo_s(sample_period))); + + // Compute the increment to interpolate + xy2_interpolation.incr_x = ((int32_t)(xy2_interpolation.target_x - xy2_interpolation.x) / xy2_interpolation.point_nbr_to_target); + xy2_interpolation.incr_y = ((int32_t)(xy2_interpolation.target_y - xy2_interpolation.y) / xy2_interpolation.point_nbr_to_target); + return true; +} + +// Set the galvo in single mode or loop mode +void Xy_BufferMode(buffer_mode_t mode) +{ + xy_buffer_mode = mode; +} + +void Xy_SetPeriod(time_luos_t period) +{ + sample_period = period; +} diff --git a/examples/projects/product/laser/lib/Galvo/xy2-100.h b/examples/projects/product/laser/lib/Galvo/xy2-100.h new file mode 100644 index 000000000..79cebf39a --- /dev/null +++ b/examples/projects/product/laser/lib/Galvo/xy2-100.h @@ -0,0 +1,30 @@ +/****************************************************************************** + * @file xy2-100 + * @brief driver for the xy2-100 protocol + * @author Luos + * @version 0.0.0 + ******************************************************************************/ +#ifndef XY2_100_H +#define XY2_100_H + +#include +#include "luos_engine.h" +#include "product_config.h" +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/******************************************************************************* + * Variables + ******************************************************************************/ + +/******************************************************************************* + * Function + ******************************************************************************/ +void Xy_Init(void); +void Xy_Start(streaming_channel_t *stream, time_luos_t period); +void Xy_Stop(void); +void Xy_BufferMode(buffer_mode_t mode); +void Xy_SetPeriod(time_luos_t period); + +#endif /* XY2_100_H */ diff --git a/examples/projects/product/laser/linker/custom_Luos_bootloader_script.ld b/examples/projects/product/laser/linker/custom_Luos_bootloader_script.ld new file mode 100644 index 000000000..dde7bb560 --- /dev/null +++ b/examples/projects/product/laser/linker/custom_Luos_bootloader_script.ld @@ -0,0 +1,175 @@ +/** + ****************************************************************************** + * @file LinkerScript.ld + * @author Auto-generated by STM32CubeIDE + * @brief Linker script for STM32L432KCUx Device from STM32L4 series + * 256Kbytes FLASH + * 64Kbytes RAM + * + * Set heap size, stack size and stack location according + * to application requirements. + * + * Set memory bank area and size if external memory is used + ****************************************************************************** + * @attention + * + *

© Copyright (c) 2020 STMicroelectronics. + * All rights reserved.

+ * + * This software component is licensed by ST under BSD 3-Clause license, + * the "License"; You may not use this file except in compliance with the + * License. You may obtain a copy of the License at: + * opensource.org/licenses/BSD-3-Clause + * + ****************************************************************************** + */ + +/* Entry Point */ +ENTRY(Reset_Handler) + +/* Highest address of the user mode stack */ +_estack = ORIGIN(RAM) + LENGTH(RAM); /* end of "RAM" Ram type memory */ + +_Min_Heap_Size = 0x200; /* required amount of heap */ +_Min_Stack_Size = 0x400; /* required amount of stack */ + +/* Memories definition */ +MEMORY +{ + RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 64K + FLASH (rx) : ORIGIN = 0x800C800, LENGTH = 206K +} + +/* Sections */ +SECTIONS +{ + /* The startup code into "FLASH" Rom type memory */ + .isr_vector : + { + . = ALIGN(4); + KEEP(*(.isr_vector)) /* Startup code */ + . = ALIGN(4); + } >FLASH + + /* The program code and other data into "FLASH" Rom type memory */ + .text : + { + . = ALIGN(4); + *(.text) /* .text sections (code) */ + *(.text*) /* .text* sections (code) */ + *(.glue_7) /* glue arm to thumb code */ + *(.glue_7t) /* glue thumb to arm code */ + *(.eh_frame) + + KEEP (*(.init)) + KEEP (*(.fini)) + + . = ALIGN(4); + _etext = .; /* define a global symbols at end of code */ + } >FLASH + + /* Constant data into "FLASH" Rom type memory */ + .rodata : + { + . = ALIGN(4); + *(.rodata) /* .rodata sections (constants, strings, etc.) */ + *(.rodata*) /* .rodata* sections (constants, strings, etc.) */ + . = ALIGN(4); + } >FLASH + + .ARM.extab : { + . = ALIGN(4); + *(.ARM.extab* .gnu.linkonce.armextab.*) + . = ALIGN(4); + } >FLASH + + .ARM : { + . = ALIGN(4); + __exidx_start = .; + *(.ARM.exidx*) + __exidx_end = .; + . = ALIGN(4); + } >FLASH + + .preinit_array : + { + . = ALIGN(4); + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP (*(.preinit_array*)) + PROVIDE_HIDDEN (__preinit_array_end = .); + . = ALIGN(4); + } >FLASH + + .init_array : + { + . = ALIGN(4); + PROVIDE_HIDDEN (__init_array_start = .); + KEEP (*(SORT(.init_array.*))) + KEEP (*(.init_array*)) + PROVIDE_HIDDEN (__init_array_end = .); + . = ALIGN(4); + } >FLASH + + .fini_array : + { + . = ALIGN(4); + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP (*(SORT(.fini_array.*))) + KEEP (*(.fini_array*)) + PROVIDE_HIDDEN (__fini_array_end = .); + . = ALIGN(4); + } >FLASH + + /* Used by the startup to initialize data */ + _sidata = LOADADDR(.data); + + /* Initialized data sections into "RAM" Ram type memory */ + .data : + { + . = ALIGN(4); + _sdata = .; /* create a global symbol at data start */ + *(.data) /* .data sections */ + *(.data*) /* .data* sections */ + + . = ALIGN(4); + _edata = .; /* define a global symbol at data end */ + + } >RAM AT> FLASH + + /* Uninitialized data section into "RAM" Ram type memory */ + . = ALIGN(4); + .bss : + { + /* This is used by the startup in order to initialize the .bss section */ + _sbss = .; /* define a global symbol at bss start */ + __bss_start__ = _sbss; + *(.bss) + *(.bss*) + *(COMMON) + + . = ALIGN(4); + _ebss = .; /* define a global symbol at bss end */ + __bss_end__ = _ebss; + } >RAM + + /* User_heap_stack section, used to check that there is enough "RAM" Ram type memory left */ + ._user_heap_stack : + { + . = ALIGN(8); + PROVIDE ( end = . ); + PROVIDE ( _end = . ); + . = . + _Min_Heap_Size; + . = . + _Min_Stack_Size; + . = ALIGN(8); + } >RAM + + /* Remove information from the compiler libraries */ + /DISCARD/ : + { + libc.a ( * ) + libm.a ( * ) + libgcc.a ( * ) + } + + .ARM.attributes 0 : { *(.ARM.attributes) } +} diff --git a/examples/projects/product/laser/node_config.h b/examples/projects/product/laser/node_config.h new file mode 100644 index 000000000..38dfb3dc9 --- /dev/null +++ b/examples/projects/product/laser/node_config.h @@ -0,0 +1,99 @@ +/****************************************************************************** + * @file node_config.h + * @brief This file allow you to use standard preprocessor definitions to + * configure your project, Luos and Luos HAL libraries + * + * # Introduction + * This file is for the luos user. You may here configure your project and + * define your custom Luos service and custom Luos command for your product + * + * Luos libraries offer a minimal standard configuration to optimize + * memory usage. In some case you have to modify standard value to fit + * with your need concerning among of data transiting through the network + * or network speed for example + * + * Luos libraries can be use with a lot a MCU family. Luos compagny give you + * a default configuration, for specific MCU family, in robus_hal_config.h. + * This configuration can be modify here to fit with you design by + * preprocessor definitions of MCU Hardware needs + * + * # Usage + * This file should be place a the root folder of your project and include + * where build flag preprocessor definitions are define in your IDE + * -include node_config.h + * + * @author Luos + * @version 0.0.0 + ******************************************************************************/ +#ifndef _NODE_CONFIG_H_ +#define _NODE_CONFIG_H_ + +/******************************************************************************* + * PROJECT DEFINITION + *******************************************************************************/ + +/******************************************************************************* + * LUOS LIBRARY DEFINITION + ******************************************************************************* + * Define | Default Value | Description + * :---------------------|------------------------------------------------------ + * MAX_LOCAL_SERVICE_NUMBER | 5 | Service number in the node + * MAX_NODE_NUMBER. | 20 | Node number in the device + * MSG_BUFFER_SIZE | 3*SIZE_MSG_MAX (405 Bytes) | Size in byte of the Luos buffer TX and RX + * MAX_MSG_NB | 2*MAX_LOCAL_SERVICE_NUMBER | Message number in Luos buffer + * MAX_NODE_NUMBER | 20 | Node number in the device + * MAX_SERVICE_NUMBER | 20 | Service number in the device + * NBR_PORT | 2 | PTP Branch number Max 8 + * NBR_RETRY | 10 | Send Retry number in case of NACK or collision + ******************************************************************************/ + +#define MAX_LOCAL_SERVICE_NUMBER 1 +#define MAX_MSG_NB 50 +#define MSG_BUFFER_SIZE 2048 + +/******************************************************************************* + * LUOS HAL LIBRARY DEFINITION +******************************************************************************* + * Define | Description + * :-----------------------|----------------------------------------------- + * MCUFREQ | Put your the MCU frequency (value in Hz) + * TIMERDIV | Timer divider clock (see your clock configuration) + * USE_CRC_HW | define to 0 if there is no Module CRC in your MCU + * USE_TX_IT | define to 1 to not use DMA transfert for Luos Tx + * + * PORT_CLOCK_ENABLE | Enable clock for port + * PTPx | A,B,C,D etc. PTP Branch Pin/Port/IRQ + * TX_LOCK_DETECT | Disable by default use if not busy flag in USART Pin/Port/IRQ + * RX_EN | Rx enable for driver RS485 always on Pin/Port + * TX_EN | Tx enable for driver RS485 Pin/Port + * COM_TX | Tx USART Com Pin/Port/Alternate + * COM_RX | Rx USART Com Pin/Port/Alternate + * PINOUT_IRQHANDLER | Callback function for Pin IRQ handler + + * ROBUS_COM_CLOCK_ENABLE | Enable clock for USART + * ROBUS_COM | USART number + * ROBUS_COM_IRQ | USART IRQ number + * ROBUS_COM_IRQHANDLER | Callback function for USART IRQ handler + + * ROBUS_DMA_CLOCK_ENABLE | Enable clock for DMA + * ROBUS_DMA | DMA number + * ROBUS_DMA_CHANNEL | DMA channel (depending on MCU DMA may need special config) + + * ROBUS_TIMER_CLOCK_ENABLE | Enable clock for Timer + * ROBUS_TIMER | Timer number + * ROBUS_TIMER_IRQ | Timer IRQ number + * ROBUS_TIMER_IRQHANDLER | Callback function for Timer IRQ handler +******************************************************************************/ + +/******************************************************************************* + * FLASH CONFIGURATION FOR APP WITH BOOTLOADER + ******************************************************************************** + * Define | Default Value | Description + * :---------------------|------------------------------------------------------ + * BOOT_START_ADDRESS | FLASH_BASE = 0x8000000 | Start address of Bootloader in flash + * SHARED_MEMORY_ADDRESS | 0x0800C000 | Start address of shared memory to save boot flag + * APP_START_ADDRESS | 0x0800C800 | Start address of application with bootloader + * APP_END_ADDRESS | FLASH_END | End address of application with bootloader + ******************************************************************************/ + +#endif /* _NODE_CONFIG_H_ */ diff --git a/examples/projects/product/laser/platformio.ini b/examples/projects/product/laser/platformio.ini new file mode 100644 index 000000000..a72a8361f --- /dev/null +++ b/examples/projects/product/laser/platformio.ini @@ -0,0 +1,37 @@ +; PlatformIO Project Configuration File +; +; Build options: build flags, source filter +; Upload options: custom upload port, speed and extra flags +; Library options: dependencies, extra library storages +; Advanced options: extra scripting +; +; Please visit documentation for the other options and examples +; https://docs.platformio.org/page/projectconf.html +[platformio] +default_envs = nucleo_l476rg + +[env] +lib_ldf_mode =off +lib_extra_dirs = + $PROJECT_DIR/../../../../../ + $PROJECT_DIR/../../../../network/ +platform = ststm32 +board = nucleo_l476rg +framework = stm32cube +lib_deps = + luos_engine@^3.1.0 + serial_network + Galvo +debug_tool = stlink +upload_protocol = stlink + +[env:nucleo_l476rg] +build_unflags = -Os +build_flags = + -O1 + -I ../ + -include node_config.h + -DUSE_HAL_DRIVER + -DUSE_FULL_LL_DRIVER + -DLUOSHAL=STM32L4 + -DSERIALHAL=STM32L476 diff --git a/examples/projects/product/laser/src/gpio.c b/examples/projects/product/laser/src/gpio.c new file mode 100644 index 000000000..0249ee815 --- /dev/null +++ b/examples/projects/product/laser/src/gpio.c @@ -0,0 +1,66 @@ +/** + ****************************************************************************** + * @file gpio.c + * @brief This file provides code for the configuration + * of all used GPIO pins. + ****************************************************************************** + * @attention + * + *

© Copyright (c) 2021 STMicroelectronics. + * All rights reserved.

+ * + * This software component is licensed by ST under BSD 3-Clause license, + * the "License"; You may not use this file except in compliance with the + * License. You may obtain a copy of the License at: + * opensource.org/licenses/BSD-3-Clause + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "gpio.h" + +/* USER CODE BEGIN 0 */ + +/* USER CODE END 0 */ + +/*----------------------------------------------------------------------------*/ +/* Configure GPIO */ +/*----------------------------------------------------------------------------*/ +/* USER CODE BEGIN 1 */ + +/* USER CODE END 1 */ + +/** Configure pins +*/ +void MX_GPIO_Init(void) +{ + + GPIO_InitTypeDef GPIO_InitStruct = {0}; + + /* GPIO Ports Clock Enable */ + __HAL_RCC_GPIOA_CLK_ENABLE(); + __HAL_RCC_GPIOB_CLK_ENABLE(); + + /*Configure GPIO pin Output Level */ + HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_RESET); + + /*Configure GPIO pin : PtPin */ + GPIO_InitStruct.Pin = BTN_Pin; + GPIO_InitStruct.Mode = GPIO_MODE_INPUT; + GPIO_InitStruct.Pull = GPIO_NOPULL; + HAL_GPIO_Init(BTN_GPIO_Port, &GPIO_InitStruct); + + /*Configure GPIO pin : PtPin */ + GPIO_InitStruct.Pin = LED_Pin; + GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; + GPIO_InitStruct.Pull = GPIO_PULLDOWN; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW; + HAL_GPIO_Init(LED_GPIO_Port, &GPIO_InitStruct); +} + +/* USER CODE BEGIN 2 */ + +/* USER CODE END 2 */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/examples/projects/product/laser/src/main.c b/examples/projects/product/laser/src/main.c new file mode 100644 index 000000000..364fa9c94 --- /dev/null +++ b/examples/projects/product/laser/src/main.c @@ -0,0 +1,193 @@ +/* USER CODE BEGIN Header */ +/** + ****************************************************************************** + * @file : main.c + * @brief : Main program body + ****************************************************************************** + * @attention + * + *

© Copyright (c) 2021 STMicroelectronics. + * All rights reserved.

+ * + * This software component is licensed by ST under BSD 3-Clause license, + * the "License"; You may not use this file except in compliance with the + * License. You may obtain a copy of the License at: + * opensource.org/licenses/BSD-3-Clause + * + ****************************************************************************** + */ +/* USER CODE END Header */ +/* Includes ------------------------------------------------------------------*/ +#include "main.h" +#include "gpio.h" + +/* Private includes ----------------------------------------------------------*/ +/* USER CODE BEGIN Includes */ +#include "luos_engine.h" +#include "serial_network.h" +#include "galvo.h" +/* USER CODE END Includes */ + +/* Private typedef -----------------------------------------------------------*/ +/* USER CODE BEGIN PTD */ +/* USER CODE END PTD */ + +/* Private define ------------------------------------------------------------*/ +/* USER CODE BEGIN PD */ +/* USER CODE END PD */ + +/* Private macro -------------------------------------------------------------*/ +/* USER CODE BEGIN PM */ + +/* USER CODE END PM */ + +/* Private variables ---------------------------------------------------------*/ + +/* USER CODE BEGIN PV */ + +/* USER CODE END PV */ + +/* Private function prototypes -----------------------------------------------*/ +void SystemClock_Config(void); +/* USER CODE BEGIN PFP */ + +/* USER CODE END PFP */ + +/* Private user code ---------------------------------------------------------*/ +/* USER CODE BEGIN 0 */ + +/* USER CODE END 0 */ + +/** + * @brief The application entry point. + * @retval int + */ +int main(void) +{ + /* USER CODE BEGIN 1 */ + + /* USER CODE END 1 */ + + /* MCU Configuration--------------------------------------------------------*/ + + /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ + HAL_Init(); + + /* USER CODE BEGIN Init */ + + /* USER CODE END Init */ + + /* Configure the system clock */ + SystemClock_Config(); + + /* USER CODE BEGIN SysInit */ + + /* USER CODE END SysInit */ + + /* Initialize all configured peripherals */ + MX_GPIO_Init(); + /* USER CODE BEGIN 2 */ + Luos_Init(); + Serial_Init(); + Galvo_Init(); + /* USER CODE END 2 */ + + /* Infinite loop */ + /* USER CODE BEGIN WHILE */ + while (1) + { + /* USER CODE END WHILE */ + + /* USER CODE BEGIN 3 */ + Luos_Loop(); + Serial_Loop(); + Galvo_Loop(); + } + /* USER CODE END 3 */ +} + +/** + * @brief System Clock Configuration + * @retval None + */ +void SystemClock_Config(void) +{ + RCC_OscInitTypeDef RCC_OscInitStruct = {0}; + RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; + + /** Initializes the RCC Oscillators according to the specified parameters + * in the RCC_OscInitTypeDef structure. + */ + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_MSI; + RCC_OscInitStruct.MSIState = RCC_MSI_ON; + RCC_OscInitStruct.MSICalibrationValue = 0; + RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_6; + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; + RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_MSI; + RCC_OscInitStruct.PLL.PLLM = 1; + RCC_OscInitStruct.PLL.PLLN = 40; + RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV7; + RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2; + RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2; + if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) + { + Error_Handler(); + } + /** Initializes the CPU, AHB and APB buses clocks + */ + RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK + | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2; + RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; + RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; + RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; + RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; + + if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK) + { + Error_Handler(); + } + /** Configure the main internal regulator output voltage + */ + if (HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1) != HAL_OK) + { + Error_Handler(); + } +} + +/* USER CODE BEGIN 4 */ + +/* USER CODE END 4 */ + +/** + * @brief This function is executed in case of error occurrence. + * @retval None + */ +void Error_Handler(void) +{ + /* USER CODE BEGIN Error_Handler_Debug */ + /* User can add his own implementation to report the HAL error return state */ + __disable_irq(); + while (1) + { + } + /* USER CODE END Error_Handler_Debug */ +} + +#ifdef USE_FULL_ASSERT +/** + * @brief Reports the name of the source file and the source line number + * where the assert_param error has occurred. + * @param file: pointer to the source file name + * @param line: assert_param error line source number + * @retval None + */ +void assert_failed(uint8_t *file, uint32_t line) +{ + /* USER CODE BEGIN 6 */ + /* User can add his own implementation to report the file name and line number, + ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ + /* USER CODE END 6 */ +} +#endif /* USE_FULL_ASSERT */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/examples/projects/product/laser/src/stm32l4xx_hal_msp.c b/examples/projects/product/laser/src/stm32l4xx_hal_msp.c new file mode 100644 index 000000000..1caf088bc --- /dev/null +++ b/examples/projects/product/laser/src/stm32l4xx_hal_msp.c @@ -0,0 +1,84 @@ +/* USER CODE BEGIN Header */ +/** + ****************************************************************************** + * @file stm32l4xx_hal_msp.c + * @brief This file provides code for the MSP Initialization + * and de-Initialization codes. + ****************************************************************************** + * @attention + * + *

© Copyright (c) 2021 STMicroelectronics. + * All rights reserved.

+ * + * This software component is licensed by ST under BSD 3-Clause license, + * the "License"; You may not use this file except in compliance with the + * License. You may obtain a copy of the License at: + * opensource.org/licenses/BSD-3-Clause + * + ****************************************************************************** + */ +/* USER CODE END Header */ + +/* Includes ------------------------------------------------------------------*/ +#include "main.h" +/* USER CODE BEGIN Includes */ + +/* USER CODE END Includes */ + +/* Private typedef -----------------------------------------------------------*/ +/* USER CODE BEGIN TD */ + +/* USER CODE END TD */ + +/* Private define ------------------------------------------------------------*/ +/* USER CODE BEGIN Define */ + +/* USER CODE END Define */ + +/* Private macro -------------------------------------------------------------*/ +/* USER CODE BEGIN Macro */ + +/* USER CODE END Macro */ + +/* Private variables ---------------------------------------------------------*/ +/* USER CODE BEGIN PV */ + +/* USER CODE END PV */ + +/* Private function prototypes -----------------------------------------------*/ +/* USER CODE BEGIN PFP */ + +/* USER CODE END PFP */ + +/* External functions --------------------------------------------------------*/ +/* USER CODE BEGIN ExternalFunctions */ + +/* USER CODE END ExternalFunctions */ + +/* USER CODE BEGIN 0 */ + +/* USER CODE END 0 */ +/** + * Initializes the Global MSP. + */ +void HAL_MspInit(void) +{ + /* USER CODE BEGIN MspInit 0 */ + + /* USER CODE END MspInit 0 */ + + __HAL_RCC_SYSCFG_CLK_ENABLE(); + __HAL_RCC_PWR_CLK_ENABLE(); + + /* System interrupt init*/ + + /* USER CODE BEGIN MspInit 1 */ + + /* USER CODE END MspInit 1 */ +} + +/* USER CODE BEGIN 1 */ + +/* USER CODE END 1 */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/examples/projects/product/laser/src/stm32l4xx_it.c b/examples/projects/product/laser/src/stm32l4xx_it.c new file mode 100644 index 000000000..259e9e3fc --- /dev/null +++ b/examples/projects/product/laser/src/stm32l4xx_it.c @@ -0,0 +1,215 @@ +/* USER CODE BEGIN Header */ +/** + ****************************************************************************** + * @file stm32l4xx_it.c + * @brief Interrupt Service Routines. + ****************************************************************************** + * @attention + * + *

© Copyright (c) 2021 STMicroelectronics. + * All rights reserved.

+ * + * This software component is licensed by ST under BSD 3-Clause license, + * the "License"; You may not use this file except in compliance with the + * License. You may obtain a copy of the License at: + * opensource.org/licenses/BSD-3-Clause + * + ****************************************************************************** + */ +/* USER CODE END Header */ + +/* Includes ------------------------------------------------------------------*/ +#include "main.h" +#include "stm32l4xx_it.h" +/* Private includes ----------------------------------------------------------*/ +/* USER CODE BEGIN Includes */ +/* USER CODE END Includes */ + +/* Private typedef -----------------------------------------------------------*/ +/* USER CODE BEGIN TD */ + +/* USER CODE END TD */ + +/* Private define ------------------------------------------------------------*/ +/* USER CODE BEGIN PD */ + +/* USER CODE END PD */ + +/* Private macro -------------------------------------------------------------*/ +/* USER CODE BEGIN PM */ + +/* USER CODE END PM */ + +/* Private variables ---------------------------------------------------------*/ +extern DMA_HandleTypeDef hdma_tim6_up; +/* USER CODE BEGIN PV */ + +/* USER CODE END PV */ + +/* Private function prototypes -----------------------------------------------*/ +/* USER CODE BEGIN PFP */ + +/* USER CODE END PFP */ + +/* Private user code ---------------------------------------------------------*/ +/* USER CODE BEGIN 0 */ + +/* USER CODE END 0 */ + +/* External variables --------------------------------------------------------*/ + +/* USER CODE BEGIN EV */ + +/* USER CODE END EV */ + +/******************************************************************************/ +/* Cortex-M4 Processor Interruption and Exception Handlers */ +/******************************************************************************/ +/** + * @brief This function handles Non maskable interrupt. + */ +void NMI_Handler(void) +{ + /* USER CODE BEGIN NonMaskableInt_IRQn 0 */ + + /* USER CODE END NonMaskableInt_IRQn 0 */ + /* USER CODE BEGIN NonMaskableInt_IRQn 1 */ + while (1) + { + } + /* USER CODE END NonMaskableInt_IRQn 1 */ +} + +/** + * @brief This function handles Hard fault interrupt. + */ +void HardFault_Handler(void) +{ + /* USER CODE BEGIN HardFault_IRQn 0 */ + + /* USER CODE END HardFault_IRQn 0 */ + while (1) + { + /* USER CODE BEGIN W1_HardFault_IRQn 0 */ + /* USER CODE END W1_HardFault_IRQn 0 */ + } +} + +/** + * @brief This function handles Memory management fault. + */ +void MemManage_Handler(void) +{ + /* USER CODE BEGIN MemoryManagement_IRQn 0 */ + + /* USER CODE END MemoryManagement_IRQn 0 */ + while (1) + { + /* USER CODE BEGIN W1_MemoryManagement_IRQn 0 */ + /* USER CODE END W1_MemoryManagement_IRQn 0 */ + } +} + +/** + * @brief This function handles Prefetch fault, memory access fault. + */ +void BusFault_Handler(void) +{ + /* USER CODE BEGIN BusFault_IRQn 0 */ + + /* USER CODE END BusFault_IRQn 0 */ + while (1) + { + /* USER CODE BEGIN W1_BusFault_IRQn 0 */ + /* USER CODE END W1_BusFault_IRQn 0 */ + } +} + +/** + * @brief This function handles Undefined instruction or illegal state. + */ +void UsageFault_Handler(void) +{ + /* USER CODE BEGIN UsageFault_IRQn 0 */ + + /* USER CODE END UsageFault_IRQn 0 */ + while (1) + { + /* USER CODE BEGIN W1_UsageFault_IRQn 0 */ + /* USER CODE END W1_UsageFault_IRQn 0 */ + } +} + +/** + * @brief This function handles System service call via SWI instruction. + */ +void SVC_Handler(void) +{ + /* USER CODE BEGIN SVCall_IRQn 0 */ + + /* USER CODE END SVCall_IRQn 0 */ + /* USER CODE BEGIN SVCall_IRQn 1 */ + + /* USER CODE END SVCall_IRQn 1 */ +} + +/** + * @brief This function handles Debug monitor. + */ +void DebugMon_Handler(void) +{ + /* USER CODE BEGIN DebugMonitor_IRQn 0 */ + + /* USER CODE END DebugMonitor_IRQn 0 */ + /* USER CODE BEGIN DebugMonitor_IRQn 1 */ + + /* USER CODE END DebugMonitor_IRQn 1 */ +} + +/** + * @brief This function handles Pendable request for system service. + */ +void PendSV_Handler(void) +{ + /* USER CODE BEGIN PendSV_IRQn 0 */ + + /* USER CODE END PendSV_IRQn 0 */ + /* USER CODE BEGIN PendSV_IRQn 1 */ + + /* USER CODE END PendSV_IRQn 1 */ +} + +/** + * @brief This function handles System tick timer. + */ +void SysTick_Handler(void) +{ + /* USER CODE BEGIN SysTick_IRQn 0 */ + + /* USER CODE END SysTick_IRQn 0 */ + HAL_IncTick(); + /* USER CODE BEGIN SysTick_IRQn 1 */ + + /* USER CODE END SysTick_IRQn 1 */ +} + +/******************************************************************************/ +/* STM32L4xx Peripheral Interrupt Handlers */ +/* Add here the Interrupt Handlers for the used peripherals. */ +/* For the available peripheral interrupt handler names, */ +/* please refer to the startup file (startup_stm32l4xx.s). */ +/******************************************************************************/ + +/* USER CODE BEGIN 1 */ +void EXTI9_5_IRQHandler(void) +{ + HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_5); +} + +void EXTI4_IRQHandler(void) +{ + HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_4); +} + +/* USER CODE END 1 */ +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/examples/projects/product/laser/src/system_stm32l4xx.c b/examples/projects/product/laser/src/system_stm32l4xx.c new file mode 100644 index 000000000..3682d36f6 --- /dev/null +++ b/examples/projects/product/laser/src/system_stm32l4xx.c @@ -0,0 +1,336 @@ +/** + ****************************************************************************** + * @file system_stm32l4xx.c + * @author MCD Application Team + * @brief CMSIS Cortex-M4 Device Peripheral Access Layer System Source File + * + * This file provides two functions and one global variable to be called from + * user application: + * - SystemInit(): This function is called at startup just after reset and + * before branch to main program. This call is made inside + * the "startup_stm32l4xx.s" file. + * + * - SystemCoreClock variable: Contains the core clock (HCLK), it can be used + * by the user application to setup the SysTick + * timer or configure other parameters. + * + * - SystemCoreClockUpdate(): Updates the variable SystemCoreClock and must + * be called whenever the core clock is changed + * during program execution. + * + * After each device reset the MSI (4 MHz) is used as system clock source. + * Then SystemInit() function is called, in "startup_stm32l4xx.s" file, to + * configure the system clock before to branch to main program. + * + * This file configures the system clock as follows: + *============================================================================= + *----------------------------------------------------------------------------- + * System Clock source | MSI + *----------------------------------------------------------------------------- + * SYSCLK(Hz) | 4000000 + *----------------------------------------------------------------------------- + * HCLK(Hz) | 4000000 + *----------------------------------------------------------------------------- + * AHB Prescaler | 1 + *----------------------------------------------------------------------------- + * APB1 Prescaler | 1 + *----------------------------------------------------------------------------- + * APB2 Prescaler | 1 + *----------------------------------------------------------------------------- + * PLL_M | 1 + *----------------------------------------------------------------------------- + * PLL_N | 8 + *----------------------------------------------------------------------------- + * PLL_P | 7 + *----------------------------------------------------------------------------- + * PLL_Q | 2 + *----------------------------------------------------------------------------- + * PLL_R | 2 + *----------------------------------------------------------------------------- + * PLLSAI1_P | NA + *----------------------------------------------------------------------------- + * PLLSAI1_Q | NA + *----------------------------------------------------------------------------- + * PLLSAI1_R | NA + *----------------------------------------------------------------------------- + * PLLSAI2_P | NA + *----------------------------------------------------------------------------- + * PLLSAI2_Q | NA + *----------------------------------------------------------------------------- + * PLLSAI2_R | NA + *----------------------------------------------------------------------------- + * Require 48MHz for USB OTG FS, | Disabled + * SDIO and RNG clock | + *----------------------------------------------------------------------------- + *============================================================================= + ****************************************************************************** + * @attention + * + *

© Copyright (c) 2017 STMicroelectronics. + * All rights reserved.

+ * + * This software component is licensed by ST under Apache License, Version 2.0, + * the "License"; You may not use this file except in compliance with the + * License. You may obtain a copy of the License at: + * opensource.org/licenses/Apache-2.0 + * + ****************************************************************************** + */ + +/** @addtogroup CMSIS + * @{ + */ + +/** @addtogroup stm32l4xx_system + * @{ + */ + +/** @addtogroup STM32L4xx_System_Private_Includes + * @{ + */ + +#include "stm32l4xx.h" + +#if !defined(HSE_VALUE) +#define HSE_VALUE 8000000U /*!< Value of the External oscillator in Hz */ +#endif /* HSE_VALUE */ + +#if !defined(MSI_VALUE) +#define MSI_VALUE 4000000U /*!< Value of the Internal oscillator in Hz*/ +#endif /* MSI_VALUE */ + +#if !defined(HSI_VALUE) +#define HSI_VALUE 16000000U /*!< Value of the Internal oscillator in Hz*/ +#endif /* HSI_VALUE */ + +/** + * @} + */ + +/** @addtogroup STM32L4xx_System_Private_TypesDefinitions + * @{ + */ + +/** + * @} + */ + +/** @addtogroup STM32L4xx_System_Private_Defines + * @{ + */ + +/************************* Miscellaneous Configuration ************************/ +/*!< Uncomment the following line if you need to relocate your vector Table in + Internal SRAM. */ +/* #define VECT_TAB_SRAM */ +#define VECT_TAB_OFFSET 0x00 /*!< Vector Table base offset field. \ + This value must be a multiple of 0x200. */ +/******************************************************************************/ +/** + * @} + */ + +/** @addtogroup STM32L4xx_System_Private_Macros + * @{ + */ + +/** + * @} + */ + +/** @addtogroup STM32L4xx_System_Private_Variables + * @{ + */ +/* The SystemCoreClock variable is updated in three ways: + 1) by calling CMSIS function SystemCoreClockUpdate() + 2) by calling HAL API function HAL_RCC_GetHCLKFreq() + 3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency + Note: If you use this function to configure the system clock; then there + is no need to call the 2 first functions listed above, since SystemCoreClock + variable is updated automatically. + */ +uint32_t SystemCoreClock = 4000000U; + +const uint8_t AHBPrescTable[16] = {0U, 0U, 0U, 0U, 0U, 0U, 0U, 0U, 1U, 2U, 3U, 4U, 6U, 7U, 8U, 9U}; +const uint8_t APBPrescTable[8] = {0U, 0U, 0U, 0U, 1U, 2U, 3U, 4U}; +const uint32_t MSIRangeTable[12] = {100000U, 200000U, 400000U, 800000U, 1000000U, 2000000U, + 4000000U, 8000000U, 16000000U, 24000000U, 32000000U, 48000000U}; +/** + * @} + */ + +/** @addtogroup STM32L4xx_System_Private_FunctionPrototypes + * @{ + */ + +/** + * @} + */ + +/** @addtogroup STM32L4xx_System_Private_Functions + * @{ + */ + +/** + * @brief Setup the microcontroller system. + * @param None + * @retval None + */ + +void SystemInit(void) +{ +/* FPU settings ------------------------------------------------------------*/ +#if (__FPU_PRESENT == 1) && (__FPU_USED == 1) + SCB->CPACR |= ((3UL << 10 * 2) | (3UL << 11 * 2)); /* set CP10 and CP11 Full Access */ +#endif + + /* Reset the RCC clock configuration to the default reset state ------------*/ + /* Set MSION bit */ + RCC->CR |= RCC_CR_MSION; + + /* Reset CFGR register */ + RCC->CFGR = 0x00000000U; + + /* Reset HSEON, CSSON , HSION, and PLLON bits */ + RCC->CR &= 0xEAF6FFFFU; + + /* Reset PLLCFGR register */ + RCC->PLLCFGR = 0x00001000U; + + /* Reset HSEBYP bit */ + RCC->CR &= 0xFFFBFFFFU; + + /* Disable all interrupts */ + RCC->CIER = 0x00000000U; + + /* Configure the Vector Table location add offset address ------------------*/ +#ifdef VECT_TAB_SRAM + SCB->VTOR = SRAM_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM */ +#else + SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH */ +#endif +} + +/** + * @brief Update SystemCoreClock variable according to Clock Register Values. + * The SystemCoreClock variable contains the core clock (HCLK), it can + * be used by the user application to setup the SysTick timer or configure + * other parameters. + * + * @note Each time the core clock (HCLK) changes, this function must be called + * to update SystemCoreClock variable value. Otherwise, any configuration + * based on this variable will be incorrect. + * + * @note - The system frequency computed by this function is not the real + * frequency in the chip. It is calculated based on the predefined + * constant and the selected clock source: + * + * - If SYSCLK source is MSI, SystemCoreClock will contain the MSI_VALUE(*) + * + * - If SYSCLK source is HSI, SystemCoreClock will contain the HSI_VALUE(**) + * + * - If SYSCLK source is HSE, SystemCoreClock will contain the HSE_VALUE(***) + * + * - If SYSCLK source is PLL, SystemCoreClock will contain the HSE_VALUE(***) + * or HSI_VALUE(*) or MSI_VALUE(*) multiplied/divided by the PLL factors. + * + * (*) MSI_VALUE is a constant defined in stm32l4xx_hal.h file (default value + * 4 MHz) but the real value may vary depending on the variations + * in voltage and temperature. + * + * (**) HSI_VALUE is a constant defined in stm32l4xx_hal.h file (default value + * 16 MHz) but the real value may vary depending on the variations + * in voltage and temperature. + * + * (***) HSE_VALUE is a constant defined in stm32l4xx_hal.h file (default value + * 8 MHz), user has to ensure that HSE_VALUE is same as the real + * frequency of the crystal used. Otherwise, this function may + * have wrong result. + * + * - The result of this function could be not correct when using fractional + * value for HSE crystal. + * + * @param None + * @retval None + */ +void SystemCoreClockUpdate(void) +{ + uint32_t tmp = 0U, msirange = 0U, pllvco = 0U, pllr = 2U, pllsource = 0U, pllm = 2U; + + /* Get MSI Range frequency--------------------------------------------------*/ + if ((RCC->CR & RCC_CR_MSIRGSEL) == RESET) + { /* MSISRANGE from RCC_CSR applies */ + msirange = (RCC->CSR & RCC_CSR_MSISRANGE) >> 8U; + } + else + { /* MSIRANGE from RCC_CR applies */ + msirange = (RCC->CR & RCC_CR_MSIRANGE) >> 4U; + } + /*MSI frequency range in HZ*/ + msirange = MSIRangeTable[msirange]; + + /* Get SYSCLK source -------------------------------------------------------*/ + switch (RCC->CFGR & RCC_CFGR_SWS) + { + case 0x00: /* MSI used as system clock source */ + SystemCoreClock = msirange; + break; + + case 0x04: /* HSI used as system clock source */ + SystemCoreClock = HSI_VALUE; + break; + + case 0x08: /* HSE used as system clock source */ + SystemCoreClock = HSE_VALUE; + break; + + case 0x0C: /* PLL used as system clock source */ + /* PLL_VCO = (HSE_VALUE or HSI_VALUE or MSI_VALUE/ PLLM) * PLLN + SYSCLK = PLL_VCO / PLLR + */ + pllsource = (RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC); + pllm = ((RCC->PLLCFGR & RCC_PLLCFGR_PLLM) >> 4U) + 1U; + + switch (pllsource) + { + case 0x02: /* HSI used as PLL clock source */ + pllvco = (HSI_VALUE / pllm); + break; + + case 0x03: /* HSE used as PLL clock source */ + pllvco = (HSE_VALUE / pllm); + break; + + default: /* MSI used as PLL clock source */ + pllvco = (msirange / pllm); + break; + } + pllvco = pllvco * ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> 8U); + pllr = (((RCC->PLLCFGR & RCC_PLLCFGR_PLLR) >> 25U) + 1U) * 2U; + SystemCoreClock = pllvco / pllr; + break; + + default: + SystemCoreClock = msirange; + break; + } + /* Compute HCLK clock frequency --------------------------------------------*/ + /* Get HCLK prescaler */ + tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4U)]; + /* HCLK clock frequency */ + SystemCoreClock >>= tmp; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/examples/projects/product/laser_galvo_control.ipynb b/examples/projects/product/laser_galvo_control.ipynb new file mode 100644 index 000000000..75fac2d5a --- /dev/null +++ b/examples/projects/product/laser_galvo_control.ipynb @@ -0,0 +1,437 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "ae88017d-aec6-46fa-b594-970fe927b7df", + "metadata": {}, + "source": [ + "# Galvo test notebook\n", + "In this notebook, you will find different use cases to use the Luos_engine Galvo example.\n", + "To make it work you need to have the Galvo controlling board connected as well as the custom gate contained in the [Product example code](https://github.com/Luos-io/luos_engine/tree/main/examples/projects/product).\n", + "By executing the next cell you should see your Galvo and Gate board, then you will be ready to use it.\n", + "If you have any questions about it please contact the [Luos_engine community on discord](http://bit.ly/JoinLuosDiscord)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "16be06ee-7ccd-4623-a719-011ab94518f5", + "metadata": {}, + "outputs": [], + "source": [ + "import time\n", + "import sys\n", + "from pyluos import Device, map_custom_service\n", + "from IPython.display import clear_output\n", + "\n", + "# Import custom service and map it\n", + "sys.path.append('/Users/nicolasrabault/Projects/luos/luos_engine/examples/projects/product')\n", + "from point_2D import Point_2D\n", + "map_custom_service(\"point_2D\", Point_2D)\n", + "\n", + "device = Device('localhost') #/dev/cu.usbserial-D308N897\n", + "#device = Device('localhost', port=8000)\n", + "print(device.nodes)" + ] + }, + { + "cell_type": "markdown", + "id": "1acb7884-d67a-4ccf-b5d1-4504a045be71", + "metadata": {}, + "source": [ + "## Send a simple point to reach" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4c96b1e1-7aaa-48c0-9bb7-28367ad6e6e5", + "metadata": {}, + "outputs": [], + "source": [ + "device.galvo.position = (4000, 4000)\n", + "device.galvo.play()" + ] + }, + { + "cell_type": "markdown", + "id": "93f100ea-5a2a-499b-8248-bc537313be2c", + "metadata": {}, + "source": [ + "## Send multiple points to reach" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d52ba92b-898c-4b0a-934c-605622fa4f0e", + "metadata": {}, + "outputs": [], + "source": [ + "# we reduce the sampling frequency to make it easy to see\n", + "device.galvo.sampling_freq = 100\n", + "device.galvo.position = [(0, 0), (20000,20000)]\n", + "device.galvo.play()" + ] + }, + { + "cell_type": "markdown", + "id": "02a99e99-bad5-4b14-9345-feaad9819b60", + "metadata": {}, + "source": [ + "By default the Galvo is in single mode. This mean that your trajectory wil be played only one time.\n", + "Now your small trajectory is loaded into the memory so you can play it again by calling `device.galvo.play()`" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c4fdcba8-b805-493b-b8a7-12370ac9fbfe", + "metadata": {}, + "outputs": [], + "source": [ + "device.galvo.play()" + ] + }, + { + "cell_type": "markdown", + "id": "ceb74118-7647-4e96-9070-8ea62c7d3106", + "metadata": {}, + "source": [ + "Alternatively you can choose to switch in continuous mode to play your trajectory in loop." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2c2e8a65-2123-4f57-8e9f-a45a107dd776", + "metadata": {}, + "outputs": [], + "source": [ + "device.galvo.continuous()\n", + "device.galvo.play()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b4cc48e4-1d3d-4ac3-a817-63929cb4dce4", + "metadata": {}, + "outputs": [], + "source": [ + "device.galvo.stop()" + ] + }, + { + "cell_type": "markdown", + "id": "3fba6baa-cd63-4fb0-9e22-3d5bfcc22e12", + "metadata": {}, + "source": [ + "# SVG demo 🎨\n", + "In this demo, we use an SVG input and display it.\n", + "First, execute the next cell to load the function then you will be able to play with it." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c2566fa9-9daf-4dc8-9cfe-b57d8cd6dc9a", + "metadata": {}, + "outputs": [], + "source": [ + "from svg.path import parse_path\n", + "from xml.dom import minidom\n", + "import pygame\n", + "import numpy as np\n", + "import requests\n", + "\n", + "# Create some functions to convert svg into trajectory\n", + "def get_point_at(path, distance, scale, offset):\n", + " pos = path.point(distance)\n", + " pos += offset\n", + " pos *= scale\n", + " return pos.real, pos.imag\n", + "\n", + "def points_from_path(path, density, scale, offset):\n", + " step = int(path.length() * density)\n", + " last_step = step - 1\n", + "\n", + " if last_step <= 0:\n", + " yield get_point_at(path, 0, scale, offset)\n", + " return\n", + "\n", + " for distance in range(step):\n", + " yield get_point_at(\n", + " path, distance / last_step, scale, offset)\n", + "\n", + "def points_from_svg(url, density=1, scale=1, offset=0):\n", + " response = requests.get(url)\n", + " if response.status_code == 200:\n", + " svg_content = response.text\n", + " doc = minidom.parseString(svg_content)\n", + " else:\n", + " print(\"Can't reach \" + url)\n", + " return\n", + "\n", + " clear_output(wait=True)\n", + " start_time = time.time()\n", + " offset = offset[0] + offset[1] * 1j\n", + " points = []\n", + " offsets = []\n", + " i = 0\n", + " for element in doc.getElementsByTagName(\"path\"):\n", + " for path in parse_path(element.getAttribute(\"d\")):\n", + " points.extend(points_from_path(\n", + " path, density, scale, offset))\n", + " i = i+1\n", + "\n", + " end_time = time.time()\n", + " elapsed_time = end_time - start_time\n", + " #print(f\"Execution time: {elapsed_time} seconds\")\n", + " return points\n", + "\n", + "def animated_svg_translation(url, density, scale, move_from, move_to, frame_nb):\n", + " frames = []\n", + " point1 = np.array(move_from)\n", + " point2 = np.array(move_to)\n", + " linear_points = np.linspace(point1, point2, frame_nb)\n", + " for offset in linear_points:\n", + " frames.append(points_from_svg(url, density=density, scale=scale, offset=(offset[0], offset[1])))\n", + " print(\"Generating animation : \" + str(offset[0]*100.0/move_to[0]) + \"%\")\n", + " return frames\n", + "\n", + "def play_animation(frames, scale):\n", + " pygame.init()\n", + " \n", + " framerate = 15\n", + " screen = pygame.display.set_mode([500, 500])\n", + " screen.fill((255, 255, 255))\n", + " running = True\n", + " frame_id = 0\n", + " device.galvo.continuous()\n", + " device.galvo.position = frames[frame_id]\n", + " time.sleep(0.1)\n", + " device.galvo.play()\n", + " while running:\n", + " frame_id = frame_id + 1\n", + " if (frame_id >= len(frames)):\n", + " frame_id = 0\n", + " screen.fill((255, 255, 255))\n", + " for point in frames[frame_id]:\n", + " point = tuple(ti/scale for ti in point)\n", + " pygame.draw.circle(screen, (0, 0, 0), point, 1)\n", + " pygame.display.update()\n", + " for event in pygame.event.get():\n", + " if event.type == pygame.QUIT:\n", + " running = False\n", + " device.galvo.position = frames[frame_id]\n", + " time.sleep(1/framerate)\n", + " pygame.quit()\n", + " device.galvo.stop()" + ] + }, + { + "cell_type": "markdown", + "id": "03331b4b-767b-4d97-8a26-7eca1a8363ff", + "metadata": {}, + "source": [ + "## Simply display a svg" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4c8d5761-7bdc-4dce-9988-4c841243c737", + "metadata": {}, + "outputs": [], + "source": [ + "# set the sample freq up to properly display it\n", + "device.galvo.sampling_freq = 4000\n", + "# load an svg image\n", + "points = points_from_svg(\"https://mirrors.creativecommons.org/presskit/icons/cc.svg\", density=0.3, scale=400, offset=(1, 100))\n", + "# we want to continuously display it\n", + "device.galvo.continuous()\n", + "device.galvo.position = points\n", + "# wait for the points to be sent before playing it\n", + "time.sleep(0.1)\n", + "device.galvo.play()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "872ef615-cd36-46cd-981d-c981d5ffe5ca", + "metadata": {}, + "outputs": [], + "source": [ + "device.galvo.stop()" + ] + }, + { + "cell_type": "markdown", + "id": "8a60b64a-4607-403c-b244-aa4004d0e380", + "metadata": {}, + "source": [ + "## Generate an animation out of the svg and play it" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d70efed7-5b49-48ea-abdc-373dcda679b7", + "metadata": {}, + "outputs": [], + "source": [ + "# compute a simple translation animation of an svg\n", + "frames = animated_svg_translation(\"https://mirrors.creativecommons.org/presskit/icons/cc.svg\", density=0.3, scale=400, move_from=(0, 0), move_to=(90, 90), frame_nb=30)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5f180167-2a74-4429-a624-fc406c4bb162", + "metadata": {}, + "outputs": [], + "source": [ + "# play the previously generated animation\n", + "# you can close the pygame window to stop it\n", + "play_animation(frames, 100)" + ] + }, + { + "cell_type": "markdown", + "id": "76e723df-d485-436f-8b90-61fc9baf5e91", + "metadata": {}, + "source": [ + "# Live audio FFT demo 🔊\n", + "In this demo, the function downloads a sound file plays it, and displays the FFT of the sound on the galvo.\n", + "First, execute the next cell to load the function then you will be able to play with it." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2c5a22a3-3176-4b5f-96ee-cdc0799808f9", + "metadata": {}, + "outputs": [], + "source": [ + "from IPython.display import Audio\n", + "from IPython.display import clear_output\n", + "import time\n", + "import numpy as np\n", + "\n", + "# Load an audio file play it and display the fft\n", + "# default file is:\n", + "#'Ignis' by Scott Buckley - released under CC-BY 4.0. www.scottbuckley.com.au\n", + "def live_display_fft(audio_file_link = 'https://www.scottbuckley.com.au/library/wp-content/uploads/2024/01/Ignis.mp3'):\n", + " rate = 44100 #I don't know how to automatically get it from URL\n", + "\n", + " # Slow down the galvo speed \n", + " device.galvo.sampling_freq = 2000\n", + " \n", + " # Create an Audio object\n", + " print(\"downloading the audio file ...\")\n", + " clear_output(wait=True)\n", + " audio_stream = Audio(url=audio_file_link, embed=True, autoplay=True)\n", + " \n", + " # Enable the galvo\n", + " fft_size = 64\n", + " X_scale = 1000\n", + " init_frame = []\n", + " Y_offset = 500\n", + " Y_scale = 1600\n", + " FPS = 20\n", + " for i in range(fft_size):\n", + " init_frame.append((i*X_scale, Y_offset))\n", + " \n", + " device.galvo.continuous()\n", + " device.galvo.position = init_frame\n", + " time.sleep(0.1)\n", + " device.galvo.play()\n", + " \n", + " # Display the audio\n", + " display(audio_stream)\n", + " \n", + " # Live animation\n", + " def chunker(seq, size):\n", + " return (seq[pos:pos + size] for pos in range(0, len(seq), size))\n", + " \n", + " sample_per_frame = int(rate/FPS)\n", + " for chunk in chunker(audio_stream.data, sample_per_frame):\n", + " chunk = np.frombuffer(chunk, dtype=np.uint8)\n", + " fft = abs(np.fft.fft(chunk, n=fft_size).real)\n", + " # Create points out of it\n", + " frame = []\n", + " freq=0\n", + " for ampl in fft:\n", + " frame.append((freq, Y_offset+(ampl*Y_scale)))\n", + " freq = freq + X_scale\n", + " device.galvo.position = frame\n", + " time.sleep(1/FPS)\n", + " device.galvo.stop()\n", + " # set the default sampling freq\n", + " device.galvo.sampling_freq = 10000" + ] + }, + { + "cell_type": "markdown", + "id": "25551a38-1a14-496c-8709-e4242c2352f0", + "metadata": {}, + "source": [ + "## Live fft\n", + "By executing this function you will play a song and live display the fft on the galvo.\n", + "You can hit pause on the reader and stop the notebook to stop the function.\n", + "You will have to manually stop the galvo if you stop the function." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c19af357-e75a-4ab4-9a34-28192d54d393", + "metadata": {}, + "outputs": [], + "source": [ + "live_display_fft()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "346f7f93-7fea-4d46-b323-c776ae552ae0", + "metadata": {}, + "outputs": [], + "source": [ + "device.galvo.stop()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "02759dee-b360-4af1-9fc0-13ecba8facbb", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.9.14" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/examples/projects/product/point_2D.py b/examples/projects/product/point_2D.py index faf9d8f17..14701a460 100644 --- a/examples/projects/product/point_2D.py +++ b/examples/projects/product/point_2D.py @@ -17,7 +17,7 @@ def __init__(self, id, alias, device): Service.__init__(self, 'Point_2D', id, alias, device) self._point = (0, 0) self._control = 0 - self._buffer_mode = _SINGLE + self._buffer_mode = self._SINGLE self._sampling_freq = 100.0 @property @@ -75,7 +75,7 @@ def sampling_freq(self): @sampling_freq.setter def sampling_freq(self, sampling_freq): self._sampling_freq = sampling_freq - self._push_value("time", 1.0 / sampling_freq) + self._push_value("sampling_freq", sampling_freq) def _update(self, new_state): diff --git a/examples/projects/product/requirements.txt b/examples/projects/product/requirements.txt new file mode 100644 index 000000000..d39f2efa9 --- /dev/null +++ b/examples/projects/product/requirements.txt @@ -0,0 +1,4 @@ +pyluos +svg.path +xml.dom +pygame diff --git a/network/serial_network/HAL/NATIVE/serial_network_hal.c b/network/serial_network/HAL/NATIVE/serial_network_hal.c index bf7ca9912..2696f2002 100644 --- a/network/serial_network/HAL/NATIVE/serial_network_hal.c +++ b/network/serial_network/HAL/NATIVE/serial_network_hal.c @@ -344,7 +344,7 @@ void SerialHAL_Send(uint8_t *data, uint16_t size) while (bytesWritten < size) { // Wait for the buffer to be empty - usleep(100); + usleep(1000); ioctl(serial_port, TIOCOUTQ, &bytes_in_buffer); bytesWritten += write(serial_port, &data[bytesWritten], size - bytesWritten); if (bytesWritten < 0)