repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
amplework/ZAlertView
Example/Pods/Target Support Files/ZAlertView/ZAlertView-umbrella.h
#ifdef __OBJC__ #import <UIKit/UIKit.h> #endif FOUNDATION_EXPORT double ZAlertViewVersionNumber; FOUNDATION_EXPORT const unsigned char ZAlertViewVersionString[];
dukemido/library_c
main.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "cJSON.h" #include "BOOK.h" #include "MEMBERS.h" #include "date.h" #include "ADMIN.h" // We're using this library as JSON PARSER https://github.com/DaveGamble/cJSON void print_menu(); void executeTask(int); int filesExists(const char*); /** * Checks if the file exists by trying to open it. * returns 1 if the file exists. * returns 0 if the file doesn`t exist. */ int fileExists(const char* filename) { int exists = 0; FILE *file; file = fopen(filename, "r"); if(file != 0) /** Found the file*/ { exists = 1; fclose(file); } return exists; } int main() { load_books_from_database();/** gets the files from folder database//books (.json) files */ load_members_from_database();/** gets the files from folder database//members (.json) files */ load_borrows_from_database();/** gets the files from folder database//borrows (.json) files */ admin_most_popular();/** print most popular books */ while(1)/** 1 so the program keeps running in an infinite loop */ { print_menu();/** prints the main menu */ } return 0; } /** * This method prints the tasks numbers and waits for the task number * Then executes it from executeTask. */ void print_menu() { printf("Menu :\n1.Book Management.\n2.Member Management.\n3.Borrow Management.\n4.Administrative actions.\n5.Save changes.\n6.Exit\n-----\n"); printf("Please choose what you want to do : "); int task; scanf("%d",&task); system("@cls"); executeTask(task); } /** This method executes the task and takes the param int which is the task id. */ void executeTask(int task) { switch(task) { case 1:/** Books Management*/ { int subTask; printf("1.Insert a book\n2.Search.\n3.Add new copies.\n4.Delete.\n5.Print all books\nPress any other number to be back\nWhat do you want to :"); scanf("%d",&subTask); if(subTask >=1 && subTask <= 5) bookTask(subTask); else system("@cls"); break; } case 2:/** Members Management*/ { int subTask; printf("1.Register a member\n2.Delete a member.\n3.Print all members.\nPress any other number to be back\nWhat do you want to :"); scanf("%d",&subTask); if(subTask >=1 && subTask <= 3) memberTask(subTask); else system("@cls"); break; } case 3:/** Borrow Management*/ { int subTask; printf("1.Borrowing book.\n2.Returning book.\n3.Print all borrows.\nPress any other number to be back\nWhat do you want to do:"); scanf("%d",&subTask); if(subTask >= 1 && subTask<= 3) borrowTask(subTask); else system("@cls"); break; } case 4:/** Admin roles.*/ { int subTask; printf("1.Overdue books.\n2.Most popular books.\nPress any other number to be back\nWhat do you want to :"); scanf("%d",&subTask); if(subTask >= 1 && subTask<= 2) administrativeTasks(subTask); else system("@cls"); break; } case 5:/** Save */ { save_delete_books(); save_delete_members(); save_borrows(); break; } case 6: exit(0); break; default: printf("Unknown task id : %d\n",task); break; } }
stevenpelley/atomic-memory-trace
src/annotation.h
// Copyright (c) 2013 <NAME> // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #ifndef PMC_ATOMIC_TRACE_H #define PMC_ATOMIC_TRACE_H // provide annotation for persistent memory traces // need general trace annotation (threads, region of interest) // persistent memory regions (pers_malloc) // and persist barriers #include <stdlib.h> #include <stdint.h> namespace atomic_trace { void* special_malloc(size_t size); void special_free(void *addr); void register_thread(int64_t thread_num); void start_roi(); void end_roi(); } #endif
SeanGau/Arduino_Core_STM8
cores/arduino/stm8/STM8_StdPeriph_Driver/stm8xx_uart1.c
<filename>cores/arduino/stm8/STM8_StdPeriph_Driver/stm8xx_uart1.c #if !defined(NO_HWSERIAL) #if defined(STM8S208) ||defined(STM8S207) || defined(STM8S007) ||defined(STM8S103) ||\ defined(STM8S003) ||defined(STM8S001) || defined(STM8S903) || defined (STM8AF52Ax) || defined (STM8AF62Ax) #include "stm8s_uart1.c" #endif /* (STM8S208) || (STM8S207) || (STM8S103) || (STM8S001) || (STM8S903) || (STM8AF52Ax) || (STM8AF62Ax) */ #endif /* !NO_HWSERIAL */
SeanGau/Arduino_Core_STM8
cores/arduino/stm8/PortNames.c
/* ******************************************************************************* * Copyright (c) 2017, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************* */ #include "PortNames.h" #include "stm8_def.h" GPIO_TypeDef *get_GPIO_Port(uint32_t port_idx) { GPIO_TypeDef *gpioPort = 0; switch (port_idx) { case PortA: gpioPort = GPIOA; break; case PortB: gpioPort = GPIOB; break; #if defined(GPIOC_BaseAddress) || defined(GPIOC_BASE) case PortC: gpioPort = GPIOC; break; #endif #if defined(GPIOD_BaseAddress) || defined(GPIOD_BASE) case PortD: gpioPort = GPIOD; break; #endif #if defined(GPIOE_BaseAddress) || defined(GPIOE_BASE) case PortE: gpioPort = GPIOE; break; #endif #if defined(GPIOF_BaseAddress) || defined(GPIOF_BASE) case PortF: gpioPort = GPIOF; break; #endif #if defined(GPIOG_BaseAddress) || defined(GPIOG_BASE) case PortG: gpioPort = GPIOG; break; #endif #if defined(GPIOH_BaseAddress) || defined(GPIOH_BASE) case PortH: gpioPort = GPIOH; break; #endif #if defined(GPIOI_BaseAddress) || defined(GPIOI_BASE) case PortI: gpioPort = GPIOI; break; #endif default: // wrong port number //TBD: error management gpioPort = 0; break; } return gpioPort; }
SeanGau/Arduino_Core_STM8
cores/arduino/stm8/STM8_StdPeriph_Driver/stm8xx_tim6.c
#if defined(STM8S903) || defined(STM8AF622x) #include "stm8s_tim6.c" #endif /* (STM8S903) || (STM8AF622x) */
SeanGau/Arduino_Core_STM8
variants/NUCLEO_8L152R8/PeripheralPins.c
<filename>variants/NUCLEO_8L152R8/PeripheralPins.c /* ******************************************************************************* * Copyright (c) 2018, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************* * Automatically generated from STM8L152R8Tx.xml */ #include "Arduino.h" #include "PeripheralPins.h" /* ===== * Note: Commented lines are alternative possibilities which are not used per default. * If you change them, you will have to know what you do * ===== */ //*** ADC *** #if !defined(NO_HWADC) const PinMap PinMap_ADC[] = { {PA_4, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_Mode_In_FL_No_IT, 0, 2, 0)}, // ADC1_IN2 {PA_5, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_Mode_In_FL_No_IT, 0, 1, 0)}, // ADC1_IN1 {PA_6, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_Mode_In_FL_No_IT, 0, 0, 0)}, // ADC1_IN0 {PB_0, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_Mode_In_FL_No_IT, 0, 18, 0)}, // ADC1_IN18 {PB_1, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_Mode_In_FL_No_IT, 0, 17, 0)}, // ADC1_IN17 {PB_2, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_Mode_In_FL_No_IT, 0, 16, 0)}, // ADC1_IN16 {PB_3, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_Mode_In_FL_No_IT, 0, 15, 0)}, // ADC1_IN15 {PB_4, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_Mode_In_FL_No_IT, 0, 14, 0)}, // ADC1_IN14 {PB_5, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_Mode_In_FL_No_IT, 0, 13, 0)}, // ADC1_IN13 {PB_6, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_Mode_In_FL_No_IT, 0, 12, 0)}, // ADC1_IN12 {PB_7, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_Mode_In_FL_No_IT, 0, 11, 0)}, // ADC1_IN11 {PC_2, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_Mode_In_FL_No_IT, 0, 6, 0)}, // ADC1_IN6 {PC_3, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_Mode_In_FL_No_IT, 0, 5, 0)}, // ADC1_IN5 {PC_4, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_Mode_In_FL_No_IT, 0, 4, 0)}, // ADC1_IN4 {PC_7, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_Mode_In_FL_No_IT, 0, 3, 0)}, // ADC1_IN3 {PD_0, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_Mode_In_FL_No_IT, 0, 22, 0)}, // ADC1_IN22 {PD_1, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_Mode_In_FL_No_IT, 0, 21, 0)}, // ADC1_IN21 {PD_2, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_Mode_In_FL_No_IT, 0, 20, 0)}, // ADC1_IN20 {PD_3, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_Mode_In_FL_No_IT, 0, 19, 0)}, // ADC1_IN19 {PD_4, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_Mode_In_FL_No_IT, 0, 10, 0)}, // ADC1_IN10 {PD_5, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_Mode_In_FL_No_IT, 0, 9, 0)}, // ADC1_IN9 {PD_6, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_Mode_In_FL_No_IT, 0, 8, 0)}, // ADC1_IN8 {PD_7, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_Mode_In_FL_No_IT, 0, 7, 0)}, // ADC1_IN7 {PE_5, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_Mode_In_FL_No_IT, 0, 23, 0)}, // ADC1_IN23 {PF_0, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_Mode_In_FL_No_IT, 0, 24, 0)}, // ADC1_IN24 {PF_1, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_Mode_In_FL_No_IT, 0, 25, 0)}, // ADC1_IN25 {NC, NP, 0} }; #endif //*** DAC *** #if !defined(NO_HWDAC) const PinMap PinMap_DAC[] = { {PF_0, DAC, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_Mode_In_FL_No_IT, 0, 1, 0)}, // DAC_OUT1 {PF_1, DAC, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_Mode_In_FL_No_IT, 0, 2, 0)}, // DAC_OUT2 {NC, NP, 0} }; #endif //*** I2C *** #if !defined(NO_HWI2C) const PinMap PinMap_I2C_SDA[] = { {PC_0, I2C1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_Mode_In_FL_No_IT, AFIO_NONE)}, {NC, NP, 0} }; #endif #if !defined(NO_HWI2C) const PinMap PinMap_I2C_SCL[] = { {PC_1, I2C1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_Mode_In_FL_No_IT, AFIO_NONE)}, {NC, NP, 0} }; #endif //*** PWM *** #if !defined(NO_HWTIM) const PinMap PinMap_PWM[] = { {PA_7, TIM5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_Mode_Out_PP_Low_Fast, AFIO_NONE, 1, 0)}, // TIM5_CH1 {PB_0, TIM2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_Mode_Out_PP_Low_Fast, AFIO_NONE, 1, 0)}, // TIM2_CH1 {PB_1, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_Mode_Out_PP_Low_Fast, AFIO_NONE, 1, 0)}, // TIM3_CH1 {PB_2, TIM2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_Mode_Out_PP_Low_Fast, AFIO_NONE, 2, 0)}, // TIM2_CH2 {PD_0, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_Mode_Out_PP_Low_Fast, AFIO_NONE, 2, 0)}, // TIM3_CH2 {PD_2, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_Mode_Out_PP_Low_Fast, AFIO_NONE, 1, 0)}, // TIM1_CH1 {PD_4, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_Mode_Out_PP_Low_Fast, AFIO_NONE, 2, 0)}, // TIM1_CH2 {PD_5, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_Mode_Out_PP_Low_Fast, AFIO_NONE, 3, 0)}, // TIM1_CH3 {PD_7, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_Mode_Out_PP_Low_Fast, AFIO_NONE, 1, 1)}, // TIM1_CH1N {PE_0, TIM5, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_Mode_Out_PP_Low_Fast, AFIO_NONE, 2, 0)}, // TIM5_CH2 {PE_1, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_Mode_Out_PP_Low_Fast, AFIO_NONE, 2, 1)}, // TIM1_CH2N {PE_2, TIM1, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_Mode_Out_PP_Low_Fast, AFIO_NONE, 3, 1)}, // TIM1_CH3N {NC, NP, 0} }; #endif //*** SERIAL *** #if !defined(NO_HWSERIAL) const PinMap PinMap_UART_TX[] = { {PA_2, USART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_Mode_Out_PP_Low_Fast, AFIO_USART1_PORTA_ENABLE)}, {PC_3, USART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_Mode_Out_PP_Low_Fast, AFIO_NONE)}, {PC_5, USART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_Mode_Out_PP_Low_Fast, AFIO_USART1_PORTC_ENABLE)}, {PE_4, USART2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_Mode_Out_PP_Low_Fast, AFIO_NONE)}, {PF_0, USART3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_Mode_Out_PP_Low_Fast, AFIO_USART3_PORTF_ENABLE)}, {PG_1, USART3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_Mode_Out_PP_Low_Fast, AFIO_NONE)}, {NC, NP, 0} }; #endif #if !defined(NO_HWSERIAL) const PinMap PinMap_UART_RX[] = { {PA_3, USART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_Mode_In_PU_No_IT, AFIO_USART1_PORTA_ENABLE)}, {PC_2, USART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_Mode_In_PU_No_IT, AFIO_NONE)}, {PC_6, USART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_Mode_In_PU_No_IT, AFIO_USART1_PORTC_ENABLE)}, {PE_3, USART2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_Mode_In_PU_No_IT, AFIO_NONE)}, {PF_1, USART3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_Mode_In_PU_No_IT, AFIO_USART3_PORTF_ENABLE)}, {PG_0, USART3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_Mode_In_PU_No_IT, AFIO_NONE)}, {NC, NP, 0} }; #endif //*** SPI *** #if !defined(NO_HWSPI) const PinMap PinMap_SPI_MOSI[] = { {PA_3, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_Mode_In_PU_No_IT, AFIO_SPI1_FULL_ENABLE)}, {PB_6, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_Mode_In_PU_No_IT, AFIO_NONE)}, {PG_6, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_Mode_In_PU_No_IT, AFIO_NONE)}, {NC, NP, 0} }; #endif #if !defined(NO_HWSPI) const PinMap PinMap_SPI_MISO[] = { {PA_2, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_Mode_In_PU_No_IT, AFIO_SPI1_FULL_ENABLE)}, {PB_7, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_Mode_In_PU_No_IT, AFIO_NONE)}, {PG_7, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_Mode_In_PU_No_IT, AFIO_NONE)}, {NC, NP, 0} }; #endif #if !defined(NO_HWSPI) const PinMap PinMap_SPI_SCLK[] = { {PB_5, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_Mode_In_PU_No_IT, AFIO_NONE)}, {PC_6, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_Mode_In_PU_No_IT, AFIO_SPI1_FULL_ENABLE)}, {PG_5, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_Mode_In_PU_No_IT, AFIO_NONE)}, {NC, NP, 0} }; #endif #if !defined(NO_HWSPI) const PinMap PinMap_SPI_SSEL[] = { {PB_4, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_Mode_In_PU_No_IT, AFIO_NONE)}, {PC_5, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_Mode_In_PU_No_IT, AFIO_SPI1_FULL_ENABLE)}, {PG_4, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_Mode_In_PU_No_IT, AFIO_NONE)}, {NC, NP, 0} }; #endif //*** CAN *** //*** No CAN_RD *** //*** No CAN_TD *** //*** QUADSPI *** //*** No QUADSPI ***
SeanGau/Arduino_Core_STM8
cores/arduino/stm8/STM8_StdPeriph_Driver/stm8xx_irtim.c
<gh_stars>100-1000 #if defined (STM8Lxx) #include "stm8l15x_irtim.c" #endif
SeanGau/Arduino_Core_STM8
cores/arduino/stm8/STM8_StdPeriph_Driver/stm8xx_comp.c
<gh_stars>100-1000 #if defined (STM8Lxx) #include "stm8l15x_comp.c" #endif
SeanGau/Arduino_Core_STM8
cores/arduino/stm8/STM8_StdPeriph_Driver/stm8xx_tim4.c
<reponame>SeanGau/Arduino_Core_STM8 #if defined(STM8Sxx) #if !defined(STM8S903) || !defined(STM8AF622x) #include "stm8s_tim4.c" #endif /* (STM8S903) || (STM8AF622x) */ #endif #if defined(STM8Lxx) #include "stm8l15x_tim4.c" #endif
SeanGau/Arduino_Core_STM8
system/Drivers/STM8Sxx_StdPeriph_Driver/src/stm8s_uart4.c
<reponame>SeanGau/Arduino_Core_STM8 /** ******************************************************************************** * @file stm8s_uart4.c * @author MCD Application Team * @version V2.3.0 * @date 16-June-2017 * @brief This file contains all the functions for the UART4 peripheral. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT 2014 STMicroelectronics</center></h2> * * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License"); * You may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.st.com/software_license_agreement_liberty_v2 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm8s_uart4.h" /** @addtogroup STM8S_StdPeriph_Driver * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /* Public functions ----------------------------------------------------------*/ /** * @addtogroup UART4_Public_Functions * @{ */ /** * @brief Deinitializes the UART peripheral. * @param None * @retval None */ void UART4_DeInit(void) { /* Clear the Idle Line Detected bit in the status register by a read to the UART4_SR register followed by a Read to the UART4_DR register */ (void)UART4->SR; (void)UART4->DR; UART4->BRR2 = UART4_BRR2_RESET_VALUE; /* Set UART4_BRR2 to reset value 0x00 */ UART4->BRR1 = UART4_BRR1_RESET_VALUE; /* Set UART4_BRR1 to reset value 0x00 */ UART4->CR1 = UART4_CR1_RESET_VALUE; /* Set UART4_CR1 to reset value 0x00 */ UART4->CR2 = UART4_CR2_RESET_VALUE; /* Set UART4_CR2 to reset value 0x00 */ UART4->CR3 = UART4_CR3_RESET_VALUE; /* Set UART4_CR3 to reset value 0x00 */ UART4->CR4 = UART4_CR4_RESET_VALUE; /* Set UART4_CR4 to reset value 0x00 */ UART4->CR5 = UART4_CR5_RESET_VALUE; /* Set UART4_CR5 to reset value 0x00 */ UART4->CR6 = UART4_CR6_RESET_VALUE; /* Set UART4_CR6 to reset value 0x00 */ } /** * @brief Initializes the UART4 according to the specified parameters. * @param BaudRate: The baudrate. * @param WordLength : This parameter can be any of the * @ref UART4_WordLength_TypeDef enumeration. * @param StopBits: This parameter can be any of the * @ref UART4_StopBits_TypeDef enumeration. * @param Parity: This parameter can be any of the * @ref UART4_Parity_TypeDef enumeration. * @param SyncMode: This parameter can be any of the * @ref UART4_SyncMode_TypeDef values. * @param Mode: This parameter can be any of the @ref UART4_Mode_TypeDef values * @retval None */ void UART4_Init(uint32_t BaudRate, UART4_WordLength_TypeDef WordLength, UART4_StopBits_TypeDef StopBits, UART4_Parity_TypeDef Parity, UART4_SyncMode_TypeDef SyncMode, UART4_Mode_TypeDef Mode) { uint8_t BRR2_1 = 0, BRR2_2 = 0; uint32_t BaudRate_Mantissa = 0, BaudRate_Mantissa100 = 0; /* Check the parameters */ assert_param(IS_UART4_BAUDRATE_OK(BaudRate)); assert_param(IS_UART4_WORDLENGTH_OK(WordLength)); assert_param(IS_UART4_STOPBITS_OK(StopBits)); assert_param(IS_UART4_PARITY_OK(Parity)); assert_param(IS_UART4_MODE_OK((uint8_t)Mode)); assert_param(IS_UART4_SYNCMODE_OK((uint8_t)SyncMode)); /* Clear the word length bit */ UART4->CR1 &= (uint8_t)(~UART4_CR1_M); /* Set the word length bit according to UART4_WordLength value */ UART4->CR1 |= (uint8_t)WordLength; /* Clear the STOP bits */ UART4->CR3 &= (uint8_t)(~UART4_CR3_STOP); /* Set the STOP bits number according to UART4_StopBits value */ UART4->CR3 |= (uint8_t)StopBits; /* Clear the Parity Control bit */ UART4->CR1 &= (uint8_t)(~(UART4_CR1_PCEN | UART4_CR1_PS )); /* Set the Parity Control bit to UART4_Parity value */ UART4->CR1 |= (uint8_t)Parity; /* Clear the LSB mantissa of UART4DIV */ UART4->BRR1 &= (uint8_t)(~UART4_BRR1_DIVM); /* Clear the MSB mantissa of UART4DIV */ UART4->BRR2 &= (uint8_t)(~UART4_BRR2_DIVM); /* Clear the Fraction bits of UART4DIV */ UART4->BRR2 &= (uint8_t)(~UART4_BRR2_DIVF); /* Set the UART4 BaudRates in BRR1 and BRR2 registers according to UART4_BaudRate value */ BaudRate_Mantissa = ((uint32_t)CLK_GetClockFreq() / (BaudRate << 4)); BaudRate_Mantissa100 = (((uint32_t)CLK_GetClockFreq() * 100) / (BaudRate << 4)); /* The fraction and MSB mantissa should be loaded in one step in the BRR2 register*/ /* Set the fraction of UARTDIV */ BRR2_1 = (uint8_t)((uint8_t)(((BaudRate_Mantissa100 - (BaudRate_Mantissa * 100)) << 4) / 100) & (uint8_t)0x0F); BRR2_2 = (uint8_t)((BaudRate_Mantissa >> 4) & (uint8_t)0xF0); UART4->BRR2 = (uint8_t)(BRR2_1 | BRR2_2); /* Set the LSB mantissa of UARTDIV */ UART4->BRR1 = (uint8_t)BaudRate_Mantissa; /* Disable the Transmitter and Receiver before setting the LBCL, CPOL and CPHA bits */ UART4->CR2 &= (uint8_t)~(UART4_CR2_TEN | UART4_CR2_REN); /* Clear the Clock Polarity, lock Phase, Last Bit Clock pulse */ UART4->CR3 &= (uint8_t)~(UART4_CR3_CPOL | UART4_CR3_CPHA | UART4_CR3_LBCL); /* Set the Clock Polarity, lock Phase, Last Bit Clock pulse */ UART4->CR3 |= (uint8_t)((uint8_t)SyncMode & (uint8_t)(UART4_CR3_CPOL | \ UART4_CR3_CPHA | UART4_CR3_LBCL)); if((uint8_t)(Mode & UART4_MODE_TX_ENABLE)) { /* Set the Transmitter Enable bit */ UART4->CR2 |= (uint8_t)UART4_CR2_TEN; } else { /* Clear the Transmitter Disable bit */ UART4->CR2 &= (uint8_t)(~UART4_CR2_TEN); } if((uint8_t)(Mode & UART4_MODE_RX_ENABLE)) { /* Set the Receiver Enable bit */ UART4->CR2 |= (uint8_t)UART4_CR2_REN; } else { /* Clear the Receiver Disable bit */ UART4->CR2 &= (uint8_t)(~UART4_CR2_REN); } /* Set the Clock Enable bit, lock Polarity, lock Phase and Last Bit Clock pulse bits according to UART4_Mode value */ if((uint8_t)(SyncMode & UART4_SYNCMODE_CLOCK_DISABLE)) { /* Clear the Clock Enable bit */ UART4->CR3 &= (uint8_t)(~UART4_CR3_CKEN); } else { UART4->CR3 |= (uint8_t)((uint8_t)SyncMode & UART4_CR3_CKEN); } } /** * @brief Enable the UART4 peripheral. * @param NewState : The new state of the UART Communication. * This parameter can be any of the @ref FunctionalState enumeration. * @retval None */ void UART4_Cmd(FunctionalState NewState) { if(NewState != DISABLE) { /* UART4 Enable */ UART4->CR1 &= (uint8_t)(~UART4_CR1_UARTD); } else { /* UART4 Disable */ UART4->CR1 |= UART4_CR1_UARTD; } } /** * @brief Enables or disables the specified UART4 interrupts. * @param UART4_IT specifies the UART4 interrupt sources to be enabled or disabled. * This parameter can be one of the following values: * - UART4_IT_LBDF: LIN Break detection interrupt * - UART4_IT_LHDF: LIN Break detection interrupt * - UART4_IT_TXE: Transmit Data Register empty interrupt * - UART4_IT_TC: Transmission complete interrupt * - UART4_IT_RXNE_OR: Receive Data register not empty/Over run error interrupt * - UART4_IT_IDLE: Idle line detection interrupt * - UART4_IT_PE: Parity Error interrupt * @param NewState new state of the specified UART4 interrupts. * This parameter can be: ENABLE or DISABLE. * @retval None */ void UART4_ITConfig(UART4_IT_TypeDef UART4_IT, FunctionalState NewState) { uint8_t uartreg = 0, itpos = 0x00; /* Check the parameters */ assert_param(IS_UART4_CONFIG_IT_OK(UART4_IT)); assert_param(IS_FUNCTIONALSTATE_OK(NewState)); /* Get the UART4 register index */ uartreg = (uint8_t)((uint16_t)UART4_IT >> 0x08); /* Get the UART4 IT index */ itpos = (uint8_t)((uint8_t)1 << (uint8_t)((uint8_t)UART4_IT & (uint8_t)0x0F)); if(NewState != DISABLE) { /* Enable the Interrupt bits according to UART4_IT mask */ if(uartreg == 0x01) { UART4->CR1 |= itpos; } else if(uartreg == 0x02) { UART4->CR2 |= itpos; } else if(uartreg == 0x03) { UART4->CR4 |= itpos; } else { UART4->CR6 |= itpos; } } else { /* Disable the interrupt bits according to UART4_IT mask */ if(uartreg == 0x01) { UART4->CR1 &= (uint8_t)(~itpos); } else if(uartreg == 0x02) { UART4->CR2 &= (uint8_t)(~itpos); } else if(uartreg == 0x03) { UART4->CR4 &= (uint8_t)(~itpos); } else { UART4->CR6 &= (uint8_t)(~itpos); } } } /** * @brief Enables or disables the UART’s Half Duplex communication. * @param NewState new state of the UART Communication. * This parameter can be: ENABLE or DISABLE. * @retval None */ void UART4_HalfDuplexCmd(FunctionalState NewState) { assert_param(IS_FUNCTIONALSTATE_OK(NewState)); if (NewState != DISABLE) { UART4->CR5 |= UART4_CR5_HDSEL; /**< UART4 Half Duplex Enable */ } else { UART4->CR5 &= (uint8_t)~UART4_CR5_HDSEL; /**< UART4 Half Duplex Disable */ } } /** * @brief Configures the UART4’s IrDA interface. * @param UART4_IrDAMode specifies the IrDA mode. * This parameter can be any of the @ref UART4_IrDAMode_TypeDef values. * @retval None */ void UART4_IrDAConfig(UART4_IrDAMode_TypeDef UART4_IrDAMode) { assert_param(IS_UART4_IRDAMODE_OK(UART4_IrDAMode)); if(UART4_IrDAMode != UART4_IRDAMODE_NORMAL) { UART4->CR5 |= UART4_CR5_IRLP; } else { UART4->CR5 &= ((uint8_t)~UART4_CR5_IRLP); } } /** * @brief Enables or disables the UART4’s IrDA interface. * @param NewState new state of the IrDA mode. * This parameter can be: ENABLE or DISABLE. * @retval None */ void UART4_IrDACmd(FunctionalState NewState) { /* Check parameters */ assert_param(IS_FUNCTIONALSTATE_OK(NewState)); if(NewState != DISABLE) { /* Enable the IrDA mode by setting the IREN bit in the CR3 register */ UART4->CR5 |= UART4_CR5_IREN; } else { /* Disable the IrDA mode by clearing the IREN bit in the CR3 register */ UART4->CR5 &= ((uint8_t)~UART4_CR5_IREN); } } /** * @brief Sets the UART4 LIN Break detection length. * @param UART4_LINBreakDetectionLength specifies the LIN break detection length. * This parameter can be any of the * @ref UART4_LINBreakDetectionLength_TypeDef values. * @retval None */ void UART4_LINBreakDetectionConfig(UART4_LINBreakDetectionLength_TypeDef UART4_LINBreakDetectionLength) { /* Check parameters */ assert_param(IS_UART4_LINBREAKDETECTIONLENGTH_OK(UART4_LINBreakDetectionLength)); if(UART4_LINBreakDetectionLength != UART4_LINBREAKDETECTIONLENGTH_10BITS) { UART4->CR4 |= UART4_CR4_LBDL; } else { UART4->CR4 &= ((uint8_t)~UART4_CR4_LBDL); } } /** * @brief Configure the UART4 peripheral. * @param UART4_Mode specifies the LIN mode. * This parameter can be any of the @ref UART4_LinMode_TypeDef values. * @param UART4_Autosync specifies the LIN automatic resynchronization mode. * This parameter can be any of the @ref UART4_LinAutosync_TypeDef values. * @param UART4_DivUp specifies the LIN divider update method. * This parameter can be any of the @ref UART4_LinDivUp_TypeDef values. * @retval None */ void UART4_LINConfig(UART4_LinMode_TypeDef UART4_Mode, UART4_LinAutosync_TypeDef UART4_Autosync, UART4_LinDivUp_TypeDef UART4_DivUp) { /* Check parameters */ assert_param(IS_UART4_SLAVE_OK(UART4_Mode)); assert_param(IS_UART4_AUTOSYNC_OK(UART4_Autosync)); assert_param(IS_UART4_DIVUP_OK(UART4_DivUp)); if(UART4_Mode != UART4_LIN_MODE_MASTER) { UART4->CR6 |= UART4_CR6_LSLV; } else { UART4->CR6 &= ((uint8_t)~UART4_CR6_LSLV); } if(UART4_Autosync != UART4_LIN_AUTOSYNC_DISABLE) { UART4->CR6 |= UART4_CR6_LASE ; } else { UART4->CR6 &= ((uint8_t)~ UART4_CR6_LASE ); } if(UART4_DivUp != UART4_LIN_DIVUP_LBRR1) { UART4->CR6 |= UART4_CR6_LDUM; } else { UART4->CR6 &= ((uint8_t)~ UART4_CR6_LDUM); } } /** * @brief Enables or disables the UART4 LIN mode. * @param NewState is new state of the UART4 LIN mode. * This parameter can be ENABLE or DISABLE * @retval None */ void UART4_LINCmd(FunctionalState NewState) { assert_param(IS_FUNCTIONALSTATE_OK(NewState)); if(NewState != DISABLE) { /* Enable the LIN mode by setting the LINE bit in the CR2 register */ UART4->CR3 |= UART4_CR3_LINEN; } else { /* Disable the LIN mode by clearing the LINE bit in the CR2 register */ UART4->CR3 &= ((uint8_t)~UART4_CR3_LINEN); } } /** * @brief Enables or disables the UART4 Smart Card mode. * @param NewState: new state of the Smart Card mode. * This parameter can be: ENABLE or DISABLE. * @retval None */ void UART4_SmartCardCmd(FunctionalState NewState) { /* Check parameters */ assert_param(IS_FUNCTIONALSTATE_OK(NewState)); if(NewState != DISABLE) { /* Enable the SC mode by setting the SCEN bit in the CR5 register */ UART4->CR5 |= UART4_CR5_SCEN; } else { /* Disable the SC mode by clearing the SCEN bit in the CR5 register */ UART4->CR5 &= ((uint8_t)(~UART4_CR5_SCEN)); } } /** * @brief Enables or disables NACK transmission. * @param NewState: new state of the Smart Card mode. * This parameter can be: ENABLE or DISABLE. * @retval None */ void UART4_SmartCardNACKCmd(FunctionalState NewState) { /* Check parameters */ assert_param(IS_FUNCTIONALSTATE_OK(NewState)); if(NewState != DISABLE) { /* Enable the NACK transmission by setting the NACK bit in the CR5 register */ UART4->CR5 |= UART4_CR5_NACK; } else { /* Disable the NACK transmission by clearing the NACK bit in the CR5 register */ UART4->CR5 &= ((uint8_t)~(UART4_CR5_NACK)); } } /** * @brief Selects the UART4 WakeUp method. * @param UART4_WakeUp: specifies the UART4 wakeup method. * This parameter can be any of the @ref UART4_WakeUp_TypeDef values. * @retval None */ void UART4_WakeUpConfig(UART4_WakeUp_TypeDef UART4_WakeUp) { assert_param(IS_UART4_WAKEUP_OK(UART4_WakeUp)); UART4->CR1 &= ((uint8_t)~UART4_CR1_WAKE); UART4->CR1 |= (uint8_t)UART4_WakeUp; } /** * @brief Determines if the UART4 is in mute mode or not. * @param NewState: new state of the UART4 mode. * This parameter can be ENABLE or DISABLE * @retval None */ void UART4_ReceiverWakeUpCmd(FunctionalState NewState) { assert_param(IS_FUNCTIONALSTATE_OK(NewState)); if(NewState != DISABLE) { /* Enable the mute mode UART4 by setting the RWU bit in the CR2 register */ UART4->CR2 |= UART4_CR2_RWU; } else { /* Disable the mute mode UART4 by clearing the RWU bit in the CR1 register */ UART4->CR2 &= ((uint8_t)~UART4_CR2_RWU); } } /** * @brief Returns the most recent received data by the UART4 peripheral. * @param None * @retval Received Data */ uint8_t UART4_ReceiveData8(void) { return ((uint8_t)UART4->DR); } /** * @brief Returns the most recent received data by the UART4 peripheral. * @param None * @retval Received Data */ uint16_t UART4_ReceiveData9(void) { uint16_t temp = 0; temp = ((uint16_t)(((uint16_t)((uint16_t)UART4->CR1 & (uint16_t)UART4_CR1_R8)) << 1)); return (uint16_t)((((uint16_t)UART4->DR) | temp) & ((uint16_t)0x01FF)); } /** * @brief Transmits 8 bit data through the UART4 peripheral. * @param Data: the data to transmit. * @retval None */ void UART4_SendData8(uint8_t Data) { /* Transmit Data */ UART4->DR = Data; } /** * @brief Transmits 9 bit data through the UART4 peripheral. * @param Data: the data to transmit. * @retval None */ void UART4_SendData9(uint16_t Data) { /* Clear the transmit data bit 8 */ UART4->CR1 &= ((uint8_t)~UART4_CR1_T8); /* Write the transmit data bit [8] */ UART4->CR1 |= (uint8_t)(((uint8_t)(Data >> 2)) & UART4_CR1_T8); /* Write the transmit data bit [0:7] */ UART4->DR = (uint8_t)(Data); } /** * @brief Transmits break characters. * @param None * @retval None */ void UART4_SendBreak(void) { UART4->CR2 |= UART4_CR2_SBK; } /** * @brief Sets the address of the UART4 node. * @param UART4_Address: Indicates the address of the UART4 node. * @retval None */ void UART4_SetAddress(uint8_t UART4_Address) { /*assert_param for x UART4_Address*/ assert_param(IS_UART4_ADDRESS_OK(UART4_Address)); /* Clear the UART4 address */ UART4->CR4 &= ((uint8_t)~UART4_CR4_ADD); /* Set the UART4 address node */ UART4->CR4 |= UART4_Address; } /** * @brief Sets the specified UART4 guard time. * @note SmartCard Mode should be Enabled * @param UART4_GuardTime: specifies the guard time. * @retval None */ void UART4_SetGuardTime(uint8_t UART4_GuardTime) { /* Set the UART4 guard time */ UART4->GTR = UART4_GuardTime; } /** * @brief Sets the system clock prescaler. * @note IrDA Low Power mode or smartcard mode should be enabled * @note This function is related to SmartCard and IrDa mode. * @param UART4_Prescaler: specifies the prescaler clock. * This parameter can be one of the following values: * @par IrDA Low Power Mode * The clock source is divided by the value given in the register (8 bits) * - 0000 0000 Reserved * - 0000 0001 divides the clock source by 1 * - 0000 0010 divides the clock source by 2 * - ... * @par Smart Card Mode * The clock source is divided by the value given in the register * (5 significant bits) multiplied by 2 * - 0 0000 Reserved * - 0 0001 divides the clock source by 2 * - 0 0010 divides the clock source by 4 * - 0 0011 divides the clock source by 6 * - ... * @retval None */ void UART4_SetPrescaler(uint8_t UART4_Prescaler) { /* Load the UART4 prescaler value*/ UART4->PSCR = UART4_Prescaler; } /** * @brief Checks whether the specified UART4 flag is set or not. * @param UART4_FLAG specifies the flag to check. * This parameter can be any of the @ref UART4_Flag_TypeDef enumeration. * @retval FlagStatus (SET or RESET) */ FlagStatus UART4_GetFlagStatus(UART4_Flag_TypeDef UART4_FLAG) { FlagStatus status = RESET; /* Check parameters */ assert_param(IS_UART4_FLAG_OK(UART4_FLAG)); /* Check the status of the specified UART4 flag*/ if(UART4_FLAG == UART4_FLAG_LBDF) { if((UART4->CR4 & (uint8_t)UART4_FLAG) != (uint8_t)0x00) { /* UART4_FLAG is set*/ status = SET; } else { /* UART4_FLAG is reset*/ status = RESET; } } else if(UART4_FLAG == UART4_FLAG_SBK) { if((UART4->CR2 & (uint8_t)UART4_FLAG) != (uint8_t)0x00) { /* UART4_FLAG is set*/ status = SET; } else { /* UART4_FLAG is reset*/ status = RESET; } } else if((UART4_FLAG == UART4_FLAG_LHDF) || (UART4_FLAG == UART4_FLAG_LSF)) { if((UART4->CR6 & (uint8_t)UART4_FLAG) != (uint8_t)0x00) { /* UART4_FLAG is set*/ status = SET; } else { /* UART4_FLAG is reset*/ status = RESET; } } else { if((UART4->SR & (uint8_t)UART4_FLAG) != (uint8_t)0x00) { /* UART4_FLAG is set*/ status = SET; } else { /* UART4_FLAG is reset*/ status = RESET; } } /* Return the UART4_FLAG status*/ return status; } /** * @brief Clears the UART4 flags. * @param UART4_FLAG specifies the flag to clear * This parameter can be any combination of the following values: * - UART4_FLAG_LBDF: LIN Break detection flag. * - UART4_FLAG_LHDF: LIN Header detection flag. * - UART4_FLAG_LSF: LIN synchrone field flag. * - UART4_FLAG_RXNE: Receive data register not empty flag. * @note: * - PE (Parity error), FE (Framing error), NE (Noise error), * OR (OverRun error) and IDLE (Idle line detected) flags are cleared * by software sequence: a read operation to UART4_SR register * (UART4_GetFlagStatus())followed by a read operation to UART4_DR * register(UART4_ReceiveData8() or UART4_ReceiveData9()). * * - RXNE flag can be also cleared by a read to the UART4_DR register * (UART4_ReceiveData8()or UART4_ReceiveData9()). * * - TC flag can be also cleared by software sequence: a read operation * to UART4_SR register (UART4_GetFlagStatus()) followed by a write * operation to UART4_DR register (UART4_SendData8() or UART4_SendData9()). * * - TXE flag is cleared only by a write to the UART4_DR register * (UART4_SendData8() or UART4_SendData9()). * * - SBK flag is cleared during the stop bit of break. * @retval None */ void UART4_ClearFlag(UART4_Flag_TypeDef UART4_FLAG) { assert_param(IS_UART4_CLEAR_FLAG_OK(UART4_FLAG)); /* Clear the Receive Register Not Empty flag */ if(UART4_FLAG == UART4_FLAG_RXNE) { UART4->SR = (uint8_t)~(UART4_SR_RXNE); } /* Clear the LIN Break Detection flag */ else if(UART4_FLAG == UART4_FLAG_LBDF) { UART4->CR4 &= (uint8_t)(~UART4_CR4_LBDF); } /* Clear the LIN Header Detection Flag */ else if(UART4_FLAG == UART4_FLAG_LHDF) { UART4->CR6 &= (uint8_t)(~UART4_CR6_LHDF); } /* Clear the LIN Synch Field flag */ else { UART4->CR6 &= (uint8_t)(~UART4_CR6_LSF); } } /** * @brief Checks whether the specified UART4 interrupt has occurred or not. * @param UART4_IT: Specifies the UART4 interrupt pending bit to check. * This parameter can be one of the following values: * - UART4_IT_LBDF: LIN Break detection interrupt * - UART4_IT_TXE: Transmit Data Register empty interrupt * - UART4_IT_TC: Transmission complete interrupt * - UART4_IT_RXNE: Receive Data register not empty interrupt * - UART4_IT_IDLE: Idle line detection interrupt * - UART4_IT_OR: OverRun Error interrupt * - UART4_IT_PE: Parity Error interrupt * @retval The state of UART4_IT (SET or RESET). */ ITStatus UART4_GetITStatus(UART4_IT_TypeDef UART4_IT) { ITStatus pendingbitstatus = RESET; uint8_t itpos = 0; uint8_t itmask1 = 0; uint8_t itmask2 = 0; uint8_t enablestatus = 0; /* Check parameters */ assert_param(IS_UART4_GET_IT_OK(UART4_IT)); /* Get the UART4 IT index*/ itpos = (uint8_t)((uint8_t)1 << (uint8_t)((uint8_t)UART4_IT & (uint8_t)0x0F)); /* Get the UART4 IT index*/ itmask1 = (uint8_t)((uint8_t)UART4_IT >> (uint8_t)4); /* Set the IT mask*/ itmask2 = (uint8_t)((uint8_t)1 << itmask1); /* Check the status of the specified UART4 pending bit*/ if(UART4_IT == UART4_IT_PE) { /* Get the UART4_ITPENDINGBIT enable bit status*/ enablestatus = (uint8_t)((uint8_t)UART4->CR1 & itmask2); /* Check the status of the specified UART4 interrupt*/ if(((UART4->SR & itpos) != (uint8_t)0x00) && enablestatus) { /* Interrupt occurred*/ pendingbitstatus = SET; } else { /* Interrupt not occurred*/ pendingbitstatus = RESET; } } else if(UART4_IT == UART4_IT_LBDF) { /* Get the UART4_IT enable bit status*/ enablestatus = (uint8_t)((uint8_t)UART4->CR4 & itmask2); /* Check the status of the specified UART4 interrupt*/ if(((UART4->CR4 & itpos) != (uint8_t)0x00) && enablestatus) { /* Interrupt occurred*/ pendingbitstatus = SET; } else { /* Interrupt not occurred*/ pendingbitstatus = RESET; } } else if(UART4_IT == UART4_IT_LHDF) { /* Get the UART4_IT enable bit status*/ enablestatus = (uint8_t)((uint8_t)UART4->CR6 & itmask2); /* Check the status of the specified UART4 interrupt*/ if(((UART4->CR6 & itpos) != (uint8_t)0x00) && enablestatus) { /* Interrupt occurred*/ pendingbitstatus = SET; } else { /* Interrupt not occurred*/ pendingbitstatus = RESET; } } else { /* Get the UART4_IT enable bit status*/ enablestatus = (uint8_t)((uint8_t)UART4->CR2 & itmask2); /* Check the status of the specified UART4 interrupt*/ if(((UART4->SR & itpos) != (uint8_t)0x00) && enablestatus) { /* Interrupt occurred*/ pendingbitstatus = SET; } else { /* Interrupt not occurred*/ pendingbitstatus = RESET; } } /* Return the UART4_IT status*/ return pendingbitstatus; } /** * @brief Clears the UART4 pending flags. * @param UART4_IT specifies the pending bit to clear * This parameter can be one of the following values: * - UART4_IT_LBDF: LIN Break detection interrupt * - UART4_IT_LHDF: LIN Header detection interrupt * - UART4_IT_RXNE: Receive Data register not empty interrupt. * @note * - PE (Parity error), FE (Framing error), NE (Noise error), * OR (OverRun error) and IDLE (Idle line detected) pending bits are * cleared by software sequence: a read operation to UART4_SR register * (UART4_GetITStatus()) followed by a read operation to UART4_DR register * (UART4_ReceiveData8() or UART4_ReceiveData9()). * * - RXNE pending bit can be also cleared by a read to the UART4_DR * register (UART4_ReceiveData8() or UART4_ReceiveData9()). * * - TC (Transmit complete) pending bit can be cleared by software * sequence: a read operation to UART4_SR register * (UART4_GetITStatus()) followed by a write operation to UART4_DR * register (UART4_SendData8()or UART4_SendData9()). * * - TXE pending bit is cleared only by a write to the UART4_DR register * (UART4_SendData8() or UART4_SendData9()). * @retval None */ void UART4_ClearITPendingBit(UART4_IT_TypeDef UART4_IT) { assert_param(IS_UART4_CLEAR_IT_OK(UART4_IT)); /* Clear the Receive Register Not Empty pending bit */ if(UART4_IT == UART4_IT_RXNE) { UART4->SR = (uint8_t)~(UART4_SR_RXNE); } /* Clear the LIN Break Detection pending bit */ else if(UART4_IT == UART4_IT_LBDF) { UART4->CR4 &= (uint8_t)~(UART4_CR4_LBDF); } /* Clear the LIN Header Detection pending bit */ else { UART4->CR6 &= (uint8_t)(~UART4_CR6_LHDF); } } /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
SeanGau/Arduino_Core_STM8
cores/arduino/stm8/stm8_def.h
<gh_stars>100-1000 #ifndef _STM8_DEF_ #define _STM8_DEF_ /** * @brief STM8 core version number */ #define STM8_CORE_VERSION_MAJOR (0x01U) /*!< [31:24] major version */ #define STM8_CORE_VERSION_MINOR (0x00U) /*!< [23:16] minor version */ #define STM8_CORE_VERSION_PATCH (0x00U) /*!< [15:8] patch version */ /* * Extra label for development: * 0: official release * [1-9]: release candidate * F[0-9]: development */ #define STM8_CORE_VERSION_EXTRA (0x00U) /*!< [7:0] extra version */ #define STM8_CORE_VERSION ((STM8_CORE_VERSION_MAJOR << 24U)\ |(STM8_CORE_VERSION_MINOR << 16U)\ |(STM8_CORE_VERSION_PATCH << 8U )\ |(STM8_CORE_VERSION_EXTRA)) #if defined(STM8Sxx) #include "stm8s.h" #elif defined(STM8Lxx) #include "stm8l15x.h" #else #error "Please select first the target STM8S/A/L device used in your application " #endif /* Here define some compatibility */ #if defined(STM8Sxx) #define AFIO_NONE 0 #if defined(ADC2) #define ADCx ADC2 #elif defined(ADC1) #define ADCx ADC1 #else #error "Can't define ADCx" #endif #endif /* STM8Sxx */ #ifdef __cplusplus extern "C" { #endif void SystemClock_Config(void); void _Error_Handler(const char *, int); #define Error_Handler() _Error_Handler(__FILE__, __LINE__) #ifdef __cplusplus } // extern "C" #endif // __cplusplus #endif //_STM8_DEF_
SeanGau/Arduino_Core_STM8
cores/arduino/stm8/STM8_StdPeriph_Driver/stm8xx_rst.c
<reponame>SeanGau/Arduino_Core_STM8<filename>cores/arduino/stm8/STM8_StdPeriph_Driver/stm8xx_rst.c #if defined (STM8Sxx) #include "stm8s_rst.c" #elif defined (STM8Lxx) #include "stm8l15x_rst.c" #endif
SeanGau/Arduino_Core_STM8
cores/arduino/stm8/STM8_StdPeriph_Driver/stm8xx_gpio.c
#if defined (STM8Sxx) #include "stm8s_gpio.c" #elif defined (STM8Lxx) #include "stm8l15x_gpio.c" #endif
SeanGau/Arduino_Core_STM8
cores/arduino/stm8/STM8_StdPeriph_Driver/stm8xx_tim3.c
#if defined(STM8S208) || defined(STM8S207) || defined(STM8S007) || defined(STM8S105) || \ defined(STM8S005) || defined(STM8AF52Ax) || defined(STM8AF62Ax) || defined(STM8AF626x) #include "stm8s_tim3.c" #endif /* (STM8S208) ||defined(STM8S207) || defined(STM8S007) ||defined(STM8S105) */ #if defined(STM8Lxx) #include "stm8l15x_tim3.c" #endif
SeanGau/Arduino_Core_STM8
cores/arduino/stm8/STM8_StdPeriph_Driver/stm8xx_syscfg.c
<reponame>SeanGau/Arduino_Core_STM8 #if defined (STM8Lxx) #include "stm8l15x_syscfg.c" #endif
SeanGau/Arduino_Core_STM8
cores/arduino/stm8/STM8_StdPeriph_Driver/stm8xx_i2c.c
#if defined (STM8Sxx) #include "stm8s_i2c.c" #elif defined (STM8L15X_MD) || defined (STM8L15X_MDP) || defined (STM8L15X_HD) || defined (STM8L15X_LD) \ || defined (STM8L05X_LD_VL) || defined (STM8L05X_MD_VL) || defined (STM8L05X_HD_VL) || defined (STM8AL31_L_MD) #include "stm8l15x_i2c.c" #endif
SeanGau/Arduino_Core_STM8
variants/NUCLEO_8S208RB/stm8s_it.c
<reponame>SeanGau/Arduino_Core_STM8 /** ****************************************************************************** * @file stm8s_it.c * @author MCD Application Team * @version V2.2.0 * @date 30-September-2014 * @brief Main Interrupt Service Routines. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT 2014 STMicroelectronics</center></h2> * * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License"); * You may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.st.com/software_license_agreement_liberty_v2 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ****************************************************************************** */ /******************************************************************************* * @IMPORTANT NOTE * This file must be place in "variants" folder for a good compilation with IAR. * If not, the interrupt vector table is not correctly generated by IAR and * interrupts will not work. ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm8_it.h" #ifdef __cplusplus extern "C" { #endif /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /* Public functions ----------------------------------------------------------*/ /** @addtogroup TIM1_Sinewave_Generation * @{ */ #ifdef _COSMIC_ extern void _stext(); /* startup routine */ #pragma section const {vector} void (* const @vector _vectab[32])() = { _stext, /* RESET */ TRAP_IRQHandler, /* TRAP */ TLI_IRQHandler, /* TLI */ AWU_IRQHandler, /* AWU */ CLK_IRQHandler, /* CLK */ EXTI_PORTA_IRQHandler, /* EXTI0 */ EXTI_PORTB_IRQHandler, /* EXTI1 */ EXTI_PORTC_IRQHandler, /* EXTI2 */ EXTI_PORTD_IRQHandler, /* EXTI3 */ EXTI_PORTE_IRQHandler, /* EXTI4 */ CAN_RX_IRQHandler, /* CAN Rx interrupt */ CAN_TX_IRQHandler, /* CAN Tx interrupt */ SPI_IRQHandler, /* SPI */ TIM1_UPD_OVF_TRG_BRK_IRQHandler, /* TIMER 1 OVF */ TIM1_CAP_COM_IRQHandler, /* TIMER 1 CAP */ TIM2_UPD_OVF_BRK_IRQHandler, /* TIMER 2 OVF */ TIM2_CAP_COM_IRQHandler, /* TIMER 2 CAP */ TIM3_UPD_OVF_BRK_IRQHandler, /* TIMER 3 OVF */ TIM3_CAP_COM_IRQHandler, /* TIMER 3 CAP */ UART1_TX_IRQHandler, /* UART1 Tx */ UART1_RX_IRQHandler, /* UART1 Rx */ I2C_IRQHandler, /* I2C */ UART3_TX_IRQHandler, /* UART3 TX */ UART3_RX_IRQHandler, /* UART3 RX */ ADC2_IRQHandler, /* ADC1 */ TIM4_UPD_OVF_IRQHandler, /* TIMER 4 OVF */ EEPROM_EEC_IRQHandler, /* EEPROM ECC */ NonHandledInterrupt, /* Reserved */ NonHandledInterrupt, /* Reserved */ NonHandledInterrupt, /* Reserved */ NonHandledInterrupt, /* Reserved */ NonHandledInterrupt, /* Reserved */ }; #endif /** * @} */ #ifdef __cplusplus } #endif /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
SeanGau/Arduino_Core_STM8
cores/arduino/stm8/STM8_StdPeriph_Driver/stm8xx_tim1.c
#if defined (STM8Sxx) #include "stm8s_tim1.c" #elif defined (STM8Lxx) #include "stm8l15x_tim1.c" #endif
SeanGau/Arduino_Core_STM8
cores/arduino/stm8/STM8_StdPeriph_Driver/stm8xx_can.c
#if defined (STM8S208) || defined (STM8AF52Ax) #include "stm8s_can.c" #endif /* (STM8S208) || (STM8AF52Ax) */
SeanGau/Arduino_Core_STM8
system/Drivers/STM8Sxx_StdPeriph_Driver/src/stm8s_uart2.c
/** ******************************************************************************** * @file stm8s_uart2.c * @author MCD Application Team * @version V2.3.0 * @date 16-June-2017 * @brief This file contains all the functions for the UART2 peripheral. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT 2014 STMicroelectronics</center></h2> * * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License"); * You may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.st.com/software_license_agreement_liberty_v2 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm8s_uart2.h" /** @addtogroup STM8S_StdPeriph_Driver * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /* Public functions ----------------------------------------------------------*/ /** * @addtogroup UART2_Public_Functions * @{ */ /** * @brief Deinitializes the UART peripheral. * @param None * @retval None */ void UART2_DeInit(void) { /* Clear the Idle Line Detected bit in the status register by a read to the UART2_SR register followed by a Read to the UART2_DR register */ (void) UART2->SR; (void)UART2->DR; UART2->BRR2 = UART2_BRR2_RESET_VALUE; /* Set UART2_BRR2 to reset value 0x00 */ UART2->BRR1 = UART2_BRR1_RESET_VALUE; /* Set UART2_BRR1 to reset value 0x00 */ UART2->CR1 = UART2_CR1_RESET_VALUE; /* Set UART2_CR1 to reset value 0x00 */ UART2->CR2 = UART2_CR2_RESET_VALUE; /* Set UART2_CR2 to reset value 0x00 */ UART2->CR3 = UART2_CR3_RESET_VALUE; /* Set UART2_CR3 to reset value 0x00 */ UART2->CR4 = UART2_CR4_RESET_VALUE; /* Set UART2_CR4 to reset value 0x00 */ UART2->CR5 = UART2_CR5_RESET_VALUE; /* Set UART2_CR5 to reset value 0x00 */ UART2->CR6 = UART2_CR6_RESET_VALUE; /* Set UART2_CR6 to reset value 0x00 */ } /** * @brief Initializes the UART2 according to the specified parameters. * @param BaudRate: The baudrate. * @param WordLength : This parameter can be any of the * @ref UART2_WordLength_TypeDef enumeration. * @param StopBits: This parameter can be any of the * @ref UART2_StopBits_TypeDef enumeration. * @param Parity: This parameter can be any of the * @ref UART2_Parity_TypeDef enumeration. * @param SyncMode: This parameter can be any of the * @ref UART2_SyncMode_TypeDef values. * @param Mode: This parameter can be any of the @ref UART2_Mode_TypeDef values * @retval None */ void UART2_Init(uint32_t BaudRate, UART2_WordLength_TypeDef WordLength, UART2_StopBits_TypeDef StopBits, UART2_Parity_TypeDef Parity, UART2_SyncMode_TypeDef SyncMode, UART2_Mode_TypeDef Mode) { uint8_t BRR2_1 = 0, BRR2_2 = 0; uint32_t BaudRate_Mantissa = 0, BaudRate_Mantissa100 = 0; /* Check the parameters */ assert_param(IS_UART2_BAUDRATE_OK(BaudRate)); assert_param(IS_UART2_WORDLENGTH_OK(WordLength)); assert_param(IS_UART2_STOPBITS_OK(StopBits)); assert_param(IS_UART2_PARITY_OK(Parity)); assert_param(IS_UART2_MODE_OK((uint8_t)Mode)); assert_param(IS_UART2_SYNCMODE_OK((uint8_t)SyncMode)); /* Clear the word length bit */ UART2->CR1 &= (uint8_t)(~UART2_CR1_M); /* Set the word length bit according to UART2_WordLength value */ UART2->CR1 |= (uint8_t)WordLength; /* Clear the STOP bits */ UART2->CR3 &= (uint8_t)(~UART2_CR3_STOP); /* Set the STOP bits number according to UART2_StopBits value */ UART2->CR3 |= (uint8_t)StopBits; /* Clear the Parity Control bit */ UART2->CR1 &= (uint8_t)(~(UART2_CR1_PCEN | UART2_CR1_PS )); /* Set the Parity Control bit to UART2_Parity value */ UART2->CR1 |= (uint8_t)Parity; /* Clear the LSB mantissa of UART2DIV */ UART2->BRR1 &= (uint8_t)(~UART2_BRR1_DIVM); /* Clear the MSB mantissa of UART2DIV */ UART2->BRR2 &= (uint8_t)(~UART2_BRR2_DIVM); /* Clear the Fraction bits of UART2DIV */ UART2->BRR2 &= (uint8_t)(~UART2_BRR2_DIVF); /* Set the UART2 BaudRates in BRR1 and BRR2 registers according to UART2_BaudRate value */ BaudRate_Mantissa = ((uint32_t)CLK_GetClockFreq() / (BaudRate << 4)); BaudRate_Mantissa100 = (((uint32_t)CLK_GetClockFreq() * 100) / (BaudRate << 4)); /* The fraction and MSB mantissa should be loaded in one step in the BRR2 register*/ /* Set the fraction of UARTDIV */ BRR2_1 = (uint8_t)((uint8_t)(((BaudRate_Mantissa100 - (BaudRate_Mantissa * 100)) << 4) / 100) & (uint8_t)0x0F); BRR2_2 = (uint8_t)((BaudRate_Mantissa >> 4) & (uint8_t)0xF0); UART2->BRR2 = (uint8_t)(BRR2_1 | BRR2_2); /* Set the LSB mantissa of UARTDIV */ UART2->BRR1 = (uint8_t)BaudRate_Mantissa; /* Disable the Transmitter and Receiver before setting the LBCL, CPOL and CPHA bits */ UART2->CR2 &= (uint8_t)~(UART2_CR2_TEN | UART2_CR2_REN); /* Clear the Clock Polarity, lock Phase, Last Bit Clock pulse */ UART2->CR3 &= (uint8_t)~(UART2_CR3_CPOL | UART2_CR3_CPHA | UART2_CR3_LBCL); /* Set the Clock Polarity, lock Phase, Last Bit Clock pulse */ UART2->CR3 |= (uint8_t)((uint8_t)SyncMode & (uint8_t)(UART2_CR3_CPOL | \ UART2_CR3_CPHA | UART2_CR3_LBCL)); if ((uint8_t)(Mode & UART2_MODE_TX_ENABLE)) { /* Set the Transmitter Enable bit */ UART2->CR2 |= (uint8_t)UART2_CR2_TEN; } else { /* Clear the Transmitter Disable bit */ UART2->CR2 &= (uint8_t)(~UART2_CR2_TEN); } if ((uint8_t)(Mode & UART2_MODE_RX_ENABLE)) { /* Set the Receiver Enable bit */ UART2->CR2 |= (uint8_t)UART2_CR2_REN; } else { /* Clear the Receiver Disable bit */ UART2->CR2 &= (uint8_t)(~UART2_CR2_REN); } /* Set the Clock Enable bit, lock Polarity, lock Phase and Last Bit Clock pulse bits according to UART2_Mode value */ if ((uint8_t)(SyncMode & UART2_SYNCMODE_CLOCK_DISABLE)) { /* Clear the Clock Enable bit */ UART2->CR3 &= (uint8_t)(~UART2_CR3_CKEN); } else { UART2->CR3 |= (uint8_t)((uint8_t)SyncMode & UART2_CR3_CKEN); } } /** * @brief Enable the UART2 peripheral. * @param NewState : The new state of the UART Communication. * This parameter can be any of the @ref FunctionalState enumeration. * @retval None */ void UART2_Cmd(FunctionalState NewState) { if (NewState != DISABLE) { /* UART2 Enable */ UART2->CR1 &= (uint8_t)(~UART2_CR1_UARTD); } else { /* UART2 Disable */ UART2->CR1 |= UART2_CR1_UARTD; } } /** * @brief Enables or disables the specified UART2 interrupts. * @param UART2_IT specifies the UART2 interrupt sources to be enabled or disabled. * This parameter can be one of the following values: * - UART2_IT_LBDF: LIN Break detection interrupt * - UART2_IT_LHDF: LIN Break detection interrupt * - UART2_IT_TXE: Transmit Data Register empty interrupt * - UART2_IT_TC: Transmission complete interrupt * - UART2_IT_RXNE_OR: Receive Data register not empty/Over run error interrupt * - UART2_IT_IDLE: Idle line detection interrupt * - UART2_IT_PE: Parity Error interrupt * @param NewState new state of the specified UART2 interrupts. * This parameter can be: ENABLE or DISABLE. * @retval None */ void UART2_ITConfig(UART2_IT_TypeDef UART2_IT, FunctionalState NewState) { uint8_t uartreg = 0, itpos = 0x00; /* Check the parameters */ assert_param(IS_UART2_CONFIG_IT_OK(UART2_IT)); assert_param(IS_FUNCTIONALSTATE_OK(NewState)); /* Get the UART2 register index */ uartreg = (uint8_t)((uint16_t)UART2_IT >> 0x08); /* Get the UART2 IT index */ itpos = (uint8_t)((uint8_t)1 << (uint8_t)((uint8_t)UART2_IT & (uint8_t)0x0F)); if (NewState != DISABLE) { /* Enable the Interrupt bits according to UART2_IT mask */ if (uartreg == 0x01) { UART2->CR1 |= itpos; } else if (uartreg == 0x02) { UART2->CR2 |= itpos; } else if (uartreg == 0x03) { UART2->CR4 |= itpos; } else { UART2->CR6 |= itpos; } } else { /* Disable the interrupt bits according to UART2_IT mask */ if (uartreg == 0x01) { UART2->CR1 &= (uint8_t)(~itpos); } else if (uartreg == 0x02) { UART2->CR2 &= (uint8_t)(~itpos); } else if (uartreg == 0x03) { UART2->CR4 &= (uint8_t)(~itpos); } else { UART2->CR6 &= (uint8_t)(~itpos); } } } /** * @brief Configures the UART2’s IrDA interface. * @param UART2_IrDAMode specifies the IrDA mode. * This parameter can be any of the @ref UART2_IrDAMode_TypeDef values. * @retval None */ void UART2_IrDAConfig(UART2_IrDAMode_TypeDef UART2_IrDAMode) { assert_param(IS_UART2_IRDAMODE_OK(UART2_IrDAMode)); if (UART2_IrDAMode != UART2_IRDAMODE_NORMAL) { UART2->CR5 |= UART2_CR5_IRLP; } else { UART2->CR5 &= ((uint8_t)~UART2_CR5_IRLP); } } /** * @brief Enables or disables the UART2’s IrDA interface. * @param NewState new state of the IrDA mode. * This parameter can be: ENABLE or DISABLE. * @retval None */ void UART2_IrDACmd(FunctionalState NewState) { /* Check parameters */ assert_param(IS_FUNCTIONALSTATE_OK(NewState)); if (NewState != DISABLE) { /* Enable the IrDA mode by setting the IREN bit in the CR3 register */ UART2->CR5 |= UART2_CR5_IREN; } else { /* Disable the IrDA mode by clearing the IREN bit in the CR3 register */ UART2->CR5 &= ((uint8_t)~UART2_CR5_IREN); } } /** * @brief Sets the UART2 LIN Break detection length. * @param UART2_LINBreakDetectionLength specifies the LIN break detection length. * This parameter can be any of the * @ref UART2_LINBreakDetectionLength_TypeDef values. * @retval None */ void UART2_LINBreakDetectionConfig(UART2_LINBreakDetectionLength_TypeDef UART2_LINBreakDetectionLength) { /* Check parameters */ assert_param(IS_UART2_LINBREAKDETECTIONLENGTH_OK(UART2_LINBreakDetectionLength)); if (UART2_LINBreakDetectionLength != UART2_LINBREAKDETECTIONLENGTH_10BITS) { UART2->CR4 |= UART2_CR4_LBDL; } else { UART2->CR4 &= ((uint8_t)~UART2_CR4_LBDL); } } /** * @brief Configure the UART2 peripheral. * @param UART2_Mode specifies the LIN mode. * This parameter can be any of the @ref UART2_LinMode_TypeDef values. * @param UART2_Autosync specifies the LIN automatic resynchronization mode. * This parameter can be any of the @ref UART2_LinAutosync_TypeDef values. * @param UART2_DivUp specifies the LIN divider update method. * This parameter can be any of the @ref UART2_LinDivUp_TypeDef values. * @retval None */ void UART2_LINConfig(UART2_LinMode_TypeDef UART2_Mode, UART2_LinAutosync_TypeDef UART2_Autosync, UART2_LinDivUp_TypeDef UART2_DivUp) { /* Check parameters */ assert_param(IS_UART2_SLAVE_OK(UART2_Mode)); assert_param(IS_UART2_AUTOSYNC_OK(UART2_Autosync)); assert_param(IS_UART2_DIVUP_OK(UART2_DivUp)); if (UART2_Mode != UART2_LIN_MODE_MASTER) { UART2->CR6 |= UART2_CR6_LSLV; } else { UART2->CR6 &= ((uint8_t)~UART2_CR6_LSLV); } if (UART2_Autosync != UART2_LIN_AUTOSYNC_DISABLE) { UART2->CR6 |= UART2_CR6_LASE ; } else { UART2->CR6 &= ((uint8_t)~ UART2_CR6_LASE ); } if (UART2_DivUp != UART2_LIN_DIVUP_LBRR1) { UART2->CR6 |= UART2_CR6_LDUM; } else { UART2->CR6 &= ((uint8_t)~ UART2_CR6_LDUM); } } /** * @brief Enables or disables the UART2 LIN mode. * @param NewState is new state of the UART2 LIN mode. * This parameter can be ENABLE or DISABLE * @retval None */ void UART2_LINCmd(FunctionalState NewState) { assert_param(IS_FUNCTIONALSTATE_OK(NewState)); if (NewState != DISABLE) { /* Enable the LIN mode by setting the LINE bit in the CR2 register */ UART2->CR3 |= UART2_CR3_LINEN; } else { /* Disable the LIN mode by clearing the LINE bit in the CR2 register */ UART2->CR3 &= ((uint8_t)~UART2_CR3_LINEN); } } /** * @brief Enables or disables the UART2 Smart Card mode. * @param NewState: new state of the Smart Card mode. * This parameter can be: ENABLE or DISABLE. * @retval None */ void UART2_SmartCardCmd(FunctionalState NewState) { /* Check parameters */ assert_param(IS_FUNCTIONALSTATE_OK(NewState)); if (NewState != DISABLE) { /* Enable the SC mode by setting the SCEN bit in the CR5 register */ UART2->CR5 |= UART2_CR5_SCEN; } else { /* Disable the SC mode by clearing the SCEN bit in the CR5 register */ UART2->CR5 &= ((uint8_t)(~UART2_CR5_SCEN)); } } /** * @brief Enables or disables NACK transmission. * @param NewState: new state of the Smart Card mode. * This parameter can be: ENABLE or DISABLE. * @retval None */ void UART2_SmartCardNACKCmd(FunctionalState NewState) { /* Check parameters */ assert_param(IS_FUNCTIONALSTATE_OK(NewState)); if (NewState != DISABLE) { /* Enable the NACK transmission by setting the NACK bit in the CR5 register */ UART2->CR5 |= UART2_CR5_NACK; } else { /* Disable the NACK transmission by clearing the NACK bit in the CR5 register */ UART2->CR5 &= ((uint8_t)~(UART2_CR5_NACK)); } } /** * @brief Selects the UART2 WakeUp method. * @param UART2_WakeUp: specifies the UART2 wakeup method. * This parameter can be any of the @ref UART2_WakeUp_TypeDef values. * @retval None */ void UART2_WakeUpConfig(UART2_WakeUp_TypeDef UART2_WakeUp) { assert_param(IS_UART2_WAKEUP_OK(UART2_WakeUp)); UART2->CR1 &= ((uint8_t)~UART2_CR1_WAKE); UART2->CR1 |= (uint8_t)UART2_WakeUp; } /** * @brief Determines if the UART2 is in mute mode or not. * @param NewState: new state of the UART2 mode. * This parameter can be ENABLE or DISABLE * @retval None */ void UART2_ReceiverWakeUpCmd(FunctionalState NewState) { assert_param(IS_FUNCTIONALSTATE_OK(NewState)); if (NewState != DISABLE) { /* Enable the mute mode UART2 by setting the RWU bit in the CR2 register */ UART2->CR2 |= UART2_CR2_RWU; } else { /* Disable the mute mode UART2 by clearing the RWU bit in the CR1 register */ UART2->CR2 &= ((uint8_t)~UART2_CR2_RWU); } } /** * @brief Returns the most recent received data by the UART2 peripheral. * @param None * @retval Received Data */ uint8_t UART2_ReceiveData8(void) { return ((uint8_t)UART2->DR); } /** * @brief Returns the most recent received data by the UART2 peripheral. * @param None * @retval Received Data */ uint16_t UART2_ReceiveData9(void) { uint16_t temp = 0; temp = ((uint16_t)(((uint16_t)((uint16_t)UART2->CR1 & (uint16_t)UART2_CR1_R8)) << 1)); return (uint16_t)((((uint16_t)UART2->DR) | temp) & ((uint16_t)0x01FF)); } /** * @brief Transmits 8 bit data through the UART2 peripheral. * @param Data: the data to transmit. * @retval None */ void UART2_SendData8(uint8_t Data) { /* Transmit Data */ UART2->DR = Data; } /** * @brief Transmits 9 bit data through the UART2 peripheral. * @param Data: the data to transmit. * @retval None */ void UART2_SendData9(uint16_t Data) { /* Clear the transmit data bit 8 */ UART2->CR1 &= ((uint8_t)~UART2_CR1_T8); /* Write the transmit data bit [8] */ UART2->CR1 |= (uint8_t)(((uint8_t)(Data >> 2)) & UART2_CR1_T8); /* Write the transmit data bit [0:7] */ UART2->DR = (uint8_t)(Data); } /** * @brief Transmits break characters. * @param None * @retval None */ void UART2_SendBreak(void) { UART2->CR2 |= UART2_CR2_SBK; } /** * @brief Sets the address of the UART2 node. * @param UART2_Address: Indicates the address of the UART2 node. * @retval None */ void UART2_SetAddress(uint8_t UART2_Address) { /*assert_param for x UART2_Address*/ assert_param(IS_UART2_ADDRESS_OK(UART2_Address)); /* Clear the UART2 address */ UART2->CR4 &= ((uint8_t)~UART2_CR4_ADD); /* Set the UART2 address node */ UART2->CR4 |= UART2_Address; } /** * @brief Sets the specified UART2 guard time. * @note SmartCard Mode should be Enabled * @param UART2_GuardTime: specifies the guard time. * @retval None */ void UART2_SetGuardTime(uint8_t UART2_GuardTime) { /* Set the UART2 guard time */ UART2->GTR = UART2_GuardTime; } /** * @brief Sets the system clock prescaler. * @note IrDA Low Power mode or smartcard mode should be enabled * @note This function is related to SmartCard and IrDa mode. * @param UART2_Prescaler: specifies the prescaler clock. * This parameter can be one of the following values: * @par IrDA Low Power Mode * The clock source is divided by the value given in the register (8 bits) * - 0000 0000 Reserved * - 0000 0001 divides the clock source by 1 * - 0000 0010 divides the clock source by 2 * - ... * @par Smart Card Mode * The clock source is divided by the value given in the register * (5 significant bits) multiped by 2 * - 0 0000 Reserved * - 0 0001 divides the clock source by 2 * - 0 0010 divides the clock source by 4 * - 0 0011 divides the clock source by 6 * - ... * @retval None */ void UART2_SetPrescaler(uint8_t UART2_Prescaler) { /* Load the UART2 prescaler value*/ UART2->PSCR = UART2_Prescaler; } /** * @brief Checks whether the specified UART2 flag is set or not. * @param UART2_FLAG specifies the flag to check. * This parameter can be any of the @ref UART2_Flag_TypeDef enumeration. * @retval FlagStatus (SET or RESET) */ FlagStatus UART2_GetFlagStatus(UART2_Flag_TypeDef UART2_FLAG) { FlagStatus status = RESET; /* Check parameters */ assert_param(IS_UART2_FLAG_OK(UART2_FLAG)); /* Check the status of the specified UART2 flag*/ if (UART2_FLAG == UART2_FLAG_LBDF) { if ((UART2->CR4 & (uint8_t)UART2_FLAG) != (uint8_t)0x00) { /* UART2_FLAG is set*/ status = SET; } else { /* UART2_FLAG is reset*/ status = RESET; } } else if (UART2_FLAG == UART2_FLAG_SBK) { if ((UART2->CR2 & (uint8_t)UART2_FLAG) != (uint8_t)0x00) { /* UART2_FLAG is set*/ status = SET; } else { /* UART2_FLAG is reset*/ status = RESET; } } else if ((UART2_FLAG == UART2_FLAG_LHDF) || (UART2_FLAG == UART2_FLAG_LSF)) { if ((UART2->CR6 & (uint8_t)UART2_FLAG) != (uint8_t)0x00) { /* UART2_FLAG is set*/ status = SET; } else { /* UART2_FLAG is reset*/ status = RESET; } } else { if ((UART2->SR & (uint8_t)UART2_FLAG) != (uint8_t)0x00) { /* UART2_FLAG is set*/ status = SET; } else { /* UART2_FLAG is reset*/ status = RESET; } } /* Return the UART2_FLAG status*/ return status; } /** * @brief Clears the UART2 flags. * @param UART2_FLAG specifies the flag to clear * This parameter can be any combination of the following values: * - UART2_FLAG_LBDF: LIN Break detection flag. * - UART2_FLAG_LHDF: LIN Header detection flag. * - UART2_FLAG_LSF: LIN synchrone field flag. * - UART2_FLAG_RXNE: Receive data register not empty flag. * @note: * - PE (Parity error), FE (Framing error), NE (Noise error), * OR (OverRun error) and IDLE (Idle line detected) flags are cleared * by software sequence: a read operation to UART2_SR register * (UART2_GetFlagStatus())followed by a read operation to UART2_DR * register(UART2_ReceiveData8() or UART2_ReceiveData9()). * * - RXNE flag can be also cleared by a read to the UART2_DR register * (UART2_ReceiveData8()or UART2_ReceiveData9()). * * - TC flag can be also cleared by software sequence: a read operation * to UART2_SR register (UART2_GetFlagStatus()) followed by a write * operation to UART2_DR register (UART2_SendData8() or UART2_SendData9()). * * - TXE flag is cleared only by a write to the UART2_DR register * (UART2_SendData8() or UART2_SendData9()). * * - SBK flag is cleared during the stop bit of break. * @retval None */ void UART2_ClearFlag(UART2_Flag_TypeDef UART2_FLAG) { assert_param(IS_UART2_CLEAR_FLAG_OK(UART2_FLAG)); /* Clear the Receive Register Not Empty flag */ if (UART2_FLAG == UART2_FLAG_RXNE) { UART2->SR = (uint8_t)~(UART2_SR_RXNE); } /* Clear the LIN Break Detection flag */ else if (UART2_FLAG == UART2_FLAG_LBDF) { UART2->CR4 &= (uint8_t)(~UART2_CR4_LBDF); } /* Clear the LIN Header Detection Flag */ else if (UART2_FLAG == UART2_FLAG_LHDF) { UART2->CR6 &= (uint8_t)(~UART2_CR6_LHDF); } /* Clear the LIN Synch Field flag */ else { UART2->CR6 &= (uint8_t)(~UART2_CR6_LSF); } } /** * @brief Checks whether the specified UART2 interrupt has occurred or not. * @param UART2_IT: Specifies the UART2 interrupt pending bit to check. * This parameter can be one of the following values: * - UART2_IT_LBDF: LIN Break detection interrupt * - UART2_IT_TXE: Transmit Data Register empty interrupt * - UART2_IT_TC: Transmission complete interrupt * - UART2_IT_RXNE: Receive Data register not empty interrupt * - UART2_IT_IDLE: Idle line detection interrupt * - UART2_IT_OR: OverRun Error interrupt * - UART2_IT_PE: Parity Error interrupt * @retval The state of UART2_IT (SET or RESET). */ ITStatus UART2_GetITStatus(UART2_IT_TypeDef UART2_IT) { ITStatus pendingbitstatus = RESET; uint8_t itpos = 0; uint8_t itmask1 = 0; uint8_t itmask2 = 0; uint8_t enablestatus = 0; /* Check parameters */ assert_param(IS_UART2_GET_IT_OK(UART2_IT)); /* Get the UART2 IT index*/ itpos = (uint8_t)((uint8_t)1 << (uint8_t)((uint8_t)UART2_IT & (uint8_t)0x0F)); /* Get the UART2 IT index*/ itmask1 = (uint8_t)((uint8_t)UART2_IT >> (uint8_t)4); /* Set the IT mask*/ itmask2 = (uint8_t)((uint8_t)1 << itmask1); /* Check the status of the specified UART2 pending bit*/ if (UART2_IT == UART2_IT_PE) { /* Get the UART2_ITPENDINGBIT enable bit status*/ enablestatus = (uint8_t)((uint8_t)UART2->CR1 & itmask2); /* Check the status of the specified UART2 interrupt*/ if (((UART2->SR & itpos) != (uint8_t)0x00) && enablestatus) { /* Interrupt occurred*/ pendingbitstatus = SET; } else { /* Interrupt not occurred*/ pendingbitstatus = RESET; } } else if (UART2_IT == UART2_IT_LBDF) { /* Get the UART2_IT enable bit status*/ enablestatus = (uint8_t)((uint8_t)UART2->CR4 & itmask2); /* Check the status of the specified UART2 interrupt*/ if (((UART2->CR4 & itpos) != (uint8_t)0x00) && enablestatus) { /* Interrupt occurred*/ pendingbitstatus = SET; } else { /* Interrupt not occurred*/ pendingbitstatus = RESET; } } else if (UART2_IT == UART2_IT_LHDF) { /* Get the UART2_IT enable bit status*/ enablestatus = (uint8_t)((uint8_t)UART2->CR6 & itmask2); /* Check the status of the specified UART2 interrupt*/ if (((UART2->CR6 & itpos) != (uint8_t)0x00) && enablestatus) { /* Interrupt occurred*/ pendingbitstatus = SET; } else { /* Interrupt not occurred*/ pendingbitstatus = RESET; } } else { /* Get the UART2_IT enable bit status*/ enablestatus = (uint8_t)((uint8_t)UART2->CR2 & itmask2); /* Check the status of the specified UART2 interrupt*/ if (((UART2->SR & itpos) != (uint8_t)0x00) && enablestatus) { /* Interrupt occurred*/ pendingbitstatus = SET; } else { /* Interrupt not occurred*/ pendingbitstatus = RESET; } } /* Return the UART2_IT status*/ return pendingbitstatus; } /** * @brief Clears the UART2 pending flags. * @param UART2_IT specifies the pending bit to clear * This parameter can be one of the following values: * - UART2_IT_LBDF: LIN Break detection interrupt * - UART2_IT_LHDF: LIN Header detection interrupt * - UART2_IT_RXNE: Receive Data register not empty interrupt. * @note * - PE (Parity error), FE (Framing error), NE (Noise error), * OR (OverRun error) and IDLE (Idle line detected) pending bits are * cleared by software sequence: a read operation to UART2_SR register * (UART2_GetITStatus()) followed by a read operation to UART2_DR register * (UART2_ReceiveData8() or UART2_ReceiveData9()). * * - RXNE pending bit can be also cleared by a read to the UART2_DR * register (UART2_ReceiveData8() or UART2_ReceiveData9()). * * - TC (Transmit complete) pending bit can be cleared by software * sequence: a read operation to UART2_SR register * (UART2_GetITStatus()) followed by a write operation to UART2_DR * register (UART2_SendData8()or UART2_SendData9()). * * - TXE pending bit is cleared only by a write to the UART2_DR register * (UART2_SendData8() or UART2_SendData9()). * @retval None */ void UART2_ClearITPendingBit(UART2_IT_TypeDef UART2_IT) { assert_param(IS_UART2_CLEAR_IT_OK(UART2_IT)); /* Clear the Receive Register Not Empty pending bit */ if (UART2_IT == UART2_IT_RXNE) { UART2->SR = (uint8_t)~(UART2_SR_RXNE); } /* Clear the LIN Break Detection pending bit */ else if (UART2_IT == UART2_IT_LBDF) { UART2->CR4 &= (uint8_t)~(UART2_CR4_LBDF); } /* Clear the LIN Header Detection pending bit */ else { UART2->CR6 &= (uint8_t)(~UART2_CR6_LHDF); } } /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
SeanGau/Arduino_Core_STM8
system/Drivers/STM8Sxx_StdPeriph_Driver/src/stm8s_tim3.c
<filename>system/Drivers/STM8Sxx_StdPeriph_Driver/src/stm8s_tim3.c /** ****************************************************************************** * @file stm8s_tim3.c * @author MCD Application Team * @version V2.3.0 * @date 16-June-2017 * @brief This file contains all the functions for the TIM3 peripheral. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT 2014 STMicroelectronics</center></h2> * * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License"); * You may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.st.com/software_license_agreement_liberty_v2 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm8s_tim3.h" /** @addtogroup STM8S_StdPeriph_Driver * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ static void TI1_Config(uint8_t TIM3_ICPolarity, uint8_t TIM3_ICSelection, uint8_t TIM3_ICFilter); static void TI2_Config(uint8_t TIM3_ICPolarity, uint8_t TIM3_ICSelection, uint8_t TIM3_ICFilter); /** * @addtogroup TIM3_Public_Functions * @{ */ /** * @brief Deinitializes the TIM3 peripheral registers to their default reset values. * @param None * @retval None */ void TIM3_DeInit(void) { TIM3->CR1 = (uint8_t)TIM3_CR1_RESET_VALUE; TIM3->IER = (uint8_t)TIM3_IER_RESET_VALUE; TIM3->SR2 = (uint8_t)TIM3_SR2_RESET_VALUE; /* Disable channels */ TIM3->CCER1 = (uint8_t)TIM3_CCER1_RESET_VALUE; /* Then reset channel registers: it also works if lock level is equal to 2 or 3 */ TIM3->CCER1 = (uint8_t)TIM3_CCER1_RESET_VALUE; TIM3->CCMR1 = (uint8_t)TIM3_CCMR1_RESET_VALUE; TIM3->CCMR2 = (uint8_t)TIM3_CCMR2_RESET_VALUE; TIM3->CNTRH = (uint8_t)TIM3_CNTRH_RESET_VALUE; TIM3->CNTRL = (uint8_t)TIM3_CNTRL_RESET_VALUE; TIM3->PSCR = (uint8_t)TIM3_PSCR_RESET_VALUE; TIM3->ARRH = (uint8_t)TIM3_ARRH_RESET_VALUE; TIM3->ARRL = (uint8_t)TIM3_ARRL_RESET_VALUE; TIM3->CCR1H = (uint8_t)TIM3_CCR1H_RESET_VALUE; TIM3->CCR1L = (uint8_t)TIM3_CCR1L_RESET_VALUE; TIM3->CCR2H = (uint8_t)TIM3_CCR2H_RESET_VALUE; TIM3->CCR2L = (uint8_t)TIM3_CCR2L_RESET_VALUE; TIM3->SR1 = (uint8_t)TIM3_SR1_RESET_VALUE; } /** * @brief Initializes the TIM3 Time Base Unit according to the specified parameters. * @param TIM3_Prescaler specifies the Prescaler from TIM3_Prescaler_TypeDef. * @param TIM3_Period specifies the Period value. * @retval None */ void TIM3_TimeBaseInit( TIM3_Prescaler_TypeDef TIM3_Prescaler, uint16_t TIM3_Period) { /* Set the Prescaler value */ TIM3->PSCR = (uint8_t)(TIM3_Prescaler); /* Set the Autoreload value */ TIM3->ARRH = (uint8_t)(TIM3_Period >> 8); TIM3->ARRL = (uint8_t)(TIM3_Period); } /** * @brief Initializes the TIM3 Channel1 according to the specified parameters. * @param TIM3_OCMode specifies the Output Compare mode from @ref TIM3_OCMode_TypeDef. * @param TIM3_OutputState specifies the Output State from @ref TIM3_OutputState_TypeDef. * @param TIM3_Pulse specifies the Pulse width value. * @param TIM3_OCPolarity specifies the Output Compare Polarity from @ref TIM3_OCPolarity_TypeDef. * @retval None */ void TIM3_OC1Init(TIM3_OCMode_TypeDef TIM3_OCMode, TIM3_OutputState_TypeDef TIM3_OutputState, uint16_t TIM3_Pulse, TIM3_OCPolarity_TypeDef TIM3_OCPolarity) { /* Check the parameters */ assert_param(IS_TIM3_OC_MODE_OK(TIM3_OCMode)); assert_param(IS_TIM3_OUTPUT_STATE_OK(TIM3_OutputState)); assert_param(IS_TIM3_OC_POLARITY_OK(TIM3_OCPolarity)); /* Disable the Channel 1: Reset the CCE Bit, Set the Output State , the Output Polarity */ TIM3->CCER1 &= (uint8_t)(~( TIM3_CCER1_CC1E | TIM3_CCER1_CC1P)); /* Set the Output State & Set the Output Polarity */ TIM3->CCER1 |= (uint8_t)((uint8_t)(TIM3_OutputState & TIM3_CCER1_CC1E ) | (uint8_t)(TIM3_OCPolarity & TIM3_CCER1_CC1P )); /* Reset the Output Compare Bits & Set the Output Compare Mode */ TIM3->CCMR1 = (uint8_t)((uint8_t)(TIM3->CCMR1 & (uint8_t)(~TIM3_CCMR_OCM)) | (uint8_t)TIM3_OCMode); /* Set the Pulse value */ TIM3->CCR1H = (uint8_t)(TIM3_Pulse >> 8); TIM3->CCR1L = (uint8_t)(TIM3_Pulse); } /** * @brief Initializes the TIM3 Channel2 according to the specified parameters. * @param TIM3_OCMode specifies the Output Compare mode from @ref TIM3_OCMode_TypeDef. * @param TIM3_OutputState specifies the Output State from @ref TIM3_OutputState_TypeDef. * @param TIM3_Pulse specifies the Pulse width value. * @param TIM3_OCPolarity specifies the Output Compare Polarity from @ref TIM3_OCPolarity_TypeDef. * @retval None */ void TIM3_OC2Init(TIM3_OCMode_TypeDef TIM3_OCMode, TIM3_OutputState_TypeDef TIM3_OutputState, uint16_t TIM3_Pulse, TIM3_OCPolarity_TypeDef TIM3_OCPolarity) { /* Check the parameters */ assert_param(IS_TIM3_OC_MODE_OK(TIM3_OCMode)); assert_param(IS_TIM3_OUTPUT_STATE_OK(TIM3_OutputState)); assert_param(IS_TIM3_OC_POLARITY_OK(TIM3_OCPolarity)); /* Disable the Channel 1: Reset the CCE Bit, Set the Output State, the Output Polarity */ TIM3->CCER1 &= (uint8_t)(~( TIM3_CCER1_CC2E | TIM3_CCER1_CC2P )); /* Set the Output State & Set the Output Polarity */ TIM3->CCER1 |= (uint8_t)((uint8_t)(TIM3_OutputState & TIM3_CCER1_CC2E ) | (uint8_t)(TIM3_OCPolarity & TIM3_CCER1_CC2P )); /* Reset the Output Compare Bits & Set the Output Compare Mode */ TIM3->CCMR2 = (uint8_t)((uint8_t)(TIM3->CCMR2 & (uint8_t)(~TIM3_CCMR_OCM)) | (uint8_t)TIM3_OCMode); /* Set the Pulse value */ TIM3->CCR2H = (uint8_t)(TIM3_Pulse >> 8); TIM3->CCR2L = (uint8_t)(TIM3_Pulse); } /** * @brief Initializes the TIM3 peripheral according to the specified parameters. * @param TIM3_Channel specifies the Input Capture Channel from @ref TIM3_Channel_TypeDef. * @param TIM3_ICPolarity specifies the Input Capture Polarity from @ref TIM3_ICPolarity_TypeDef. * @param TIM3_ICSelection specifies the Input Capture Selection from @ref TIM3_ICSelection_TypeDef. * @param TIM3_ICPrescaler specifies the Input Capture Prescaler from @ref TIM3_ICPSC_TypeDef. * @param TIM3_ICFilter specifies the Input Capture Filter value (value can be an integer from 0x00 to 0x0F). * @retval None */ void TIM3_ICInit(TIM3_Channel_TypeDef TIM3_Channel, TIM3_ICPolarity_TypeDef TIM3_ICPolarity, TIM3_ICSelection_TypeDef TIM3_ICSelection, TIM3_ICPSC_TypeDef TIM3_ICPrescaler, uint8_t TIM3_ICFilter) { /* Check the parameters */ assert_param(IS_TIM3_CHANNEL_OK(TIM3_Channel)); assert_param(IS_TIM3_IC_POLARITY_OK(TIM3_ICPolarity)); assert_param(IS_TIM3_IC_SELECTION_OK(TIM3_ICSelection)); assert_param(IS_TIM3_IC_PRESCALER_OK(TIM3_ICPrescaler)); assert_param(IS_TIM3_IC_FILTER_OK(TIM3_ICFilter)); if (TIM3_Channel != TIM3_CHANNEL_2) { /* TI1 Configuration */ TI1_Config((uint8_t)TIM3_ICPolarity, (uint8_t)TIM3_ICSelection, (uint8_t)TIM3_ICFilter); /* Set the Input Capture Prescaler value */ TIM3_SetIC1Prescaler(TIM3_ICPrescaler); } else { /* TI2 Configuration */ TI2_Config((uint8_t)TIM3_ICPolarity, (uint8_t)TIM3_ICSelection, (uint8_t)TIM3_ICFilter); /* Set the Input Capture Prescaler value */ TIM3_SetIC2Prescaler(TIM3_ICPrescaler); } } /** * @brief Configures the TIM3 peripheral in PWM Input Mode according to the specified parameters. * @param TIM3_Channel specifies the Input Capture Channel from @ref TIM3_Channel_TypeDef. * @param TIM3_ICPolarity specifies the Input Capture Polarity from @ref TIM3_ICPolarity_TypeDef. * @param TIM3_ICSelection specifies the Input Capture Selection from @ref TIM3_ICSelection_TypeDef. * @param TIM3_ICPrescaler specifies the Input Capture Prescaler from @ref TIM3_ICPSC_TypeDef. * @param TIM3_ICFilter specifies the Input Capture Filter value (value can be an integer from 0x00 to 0x0F). * @retval None */ void TIM3_PWMIConfig(TIM3_Channel_TypeDef TIM3_Channel, TIM3_ICPolarity_TypeDef TIM3_ICPolarity, TIM3_ICSelection_TypeDef TIM3_ICSelection, TIM3_ICPSC_TypeDef TIM3_ICPrescaler, uint8_t TIM3_ICFilter) { uint8_t icpolarity = (uint8_t)TIM3_ICPOLARITY_RISING; uint8_t icselection = (uint8_t)TIM3_ICSELECTION_DIRECTTI; /* Check the parameters */ assert_param(IS_TIM3_PWMI_CHANNEL_OK(TIM3_Channel)); assert_param(IS_TIM3_IC_POLARITY_OK(TIM3_ICPolarity)); assert_param(IS_TIM3_IC_SELECTION_OK(TIM3_ICSelection)); assert_param(IS_TIM3_IC_PRESCALER_OK(TIM3_ICPrescaler)); /* Select the Opposite Input Polarity */ if (TIM3_ICPolarity != TIM3_ICPOLARITY_FALLING) { icpolarity = (uint8_t)TIM3_ICPOLARITY_FALLING; } else { icpolarity = (uint8_t)TIM3_ICPOLARITY_RISING; } /* Select the Opposite Input */ if (TIM3_ICSelection == TIM3_ICSELECTION_DIRECTTI) { icselection = (uint8_t)TIM3_ICSELECTION_INDIRECTTI; } else { icselection = (uint8_t)TIM3_ICSELECTION_DIRECTTI; } if (TIM3_Channel != TIM3_CHANNEL_2) { /* TI1 Configuration */ TI1_Config((uint8_t)TIM3_ICPolarity, (uint8_t)TIM3_ICSelection, (uint8_t)TIM3_ICFilter); /* Set the Input Capture Prescaler value */ TIM3_SetIC1Prescaler(TIM3_ICPrescaler); /* TI2 Configuration */ TI2_Config(icpolarity, icselection, TIM3_ICFilter); /* Set the Input Capture Prescaler value */ TIM3_SetIC2Prescaler(TIM3_ICPrescaler); } else { /* TI2 Configuration */ TI2_Config((uint8_t)TIM3_ICPolarity, (uint8_t)TIM3_ICSelection, (uint8_t)TIM3_ICFilter); /* Set the Input Capture Prescaler value */ TIM3_SetIC2Prescaler(TIM3_ICPrescaler); /* TI1 Configuration */ TI1_Config(icpolarity, icselection, TIM3_ICFilter); /* Set the Input Capture Prescaler value */ TIM3_SetIC1Prescaler(TIM3_ICPrescaler); } } /** * @brief Enables or disables the TIM3 peripheral. * @param NewState new state of the TIM3 peripheral. This parameter can * be ENABLE or DISABLE. * @retval None */ void TIM3_Cmd(FunctionalState NewState) { /* Check the parameters */ assert_param(IS_FUNCTIONALSTATE_OK(NewState)); /* set or Reset the CEN Bit */ if (NewState != DISABLE) { TIM3->CR1 |= (uint8_t)TIM3_CR1_CEN; } else { TIM3->CR1 &= (uint8_t)(~TIM3_CR1_CEN); } } /** * @brief Enables or disables the specified TIM3 interrupts. * @param NewState new state of the TIM3 peripheral. * This parameter can be: ENABLE or DISABLE. * @param TIM3_IT specifies the TIM3 interrupts sources to be enabled or disabled. * This parameter can be any combination of the following values: * - TIM3_IT_UPDATE: TIM3 update Interrupt source * - TIM3_IT_CC1: TIM3 Capture Compare 1 Interrupt source * - TIM3_IT_CC2: TIM3 Capture Compare 2 Interrupt source * - TIM3_IT_CC3: TIM3 Capture Compare 3 Interrupt source * @param NewState new state of the TIM3 peripheral. * @retval None */ void TIM3_ITConfig(TIM3_IT_TypeDef TIM3_IT, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_TIM3_IT_OK(TIM3_IT)); assert_param(IS_FUNCTIONALSTATE_OK(NewState)); if (NewState != DISABLE) { /* Enable the Interrupt sources */ TIM3->IER |= (uint8_t)TIM3_IT; } else { /* Disable the Interrupt sources */ TIM3->IER &= (uint8_t)(~TIM3_IT); } } /** * @brief Enables or Disables the TIM3 Update event. * @param NewState new state of the TIM3 peripheral Preload register. This parameter can * be ENABLE or DISABLE. * @retval None */ void TIM3_UpdateDisableConfig(FunctionalState NewState) { /* Check the parameters */ assert_param(IS_FUNCTIONALSTATE_OK(NewState)); /* Set or Reset the UDIS Bit */ if (NewState != DISABLE) { TIM3->CR1 |= TIM3_CR1_UDIS; } else { TIM3->CR1 &= (uint8_t)(~TIM3_CR1_UDIS); } } /** * @brief Selects the TIM3 Update Request Interrupt source. * @param TIM3_UpdateSource specifies the Update source. * This parameter can be one of the following values * - TIM3_UPDATESOURCE_REGULAR * - TIM3_UPDATESOURCE_GLOBAL * @retval None */ void TIM3_UpdateRequestConfig(TIM3_UpdateSource_TypeDef TIM3_UpdateSource) { /* Check the parameters */ assert_param(IS_TIM3_UPDATE_SOURCE_OK(TIM3_UpdateSource)); /* Set or Reset the URS Bit */ if (TIM3_UpdateSource != TIM3_UPDATESOURCE_GLOBAL) { TIM3->CR1 |= TIM3_CR1_URS; } else { TIM3->CR1 &= (uint8_t)(~TIM3_CR1_URS); } } /** * @brief Selects the TIM3’s One Pulse Mode. * @param TIM3_OPMode specifies the OPM Mode to be used. * This parameter can be one of the following values * - TIM3_OPMODE_SINGLE * - TIM3_OPMODE_REPETITIVE * @retval None */ void TIM3_SelectOnePulseMode(TIM3_OPMode_TypeDef TIM3_OPMode) { /* Check the parameters */ assert_param(IS_TIM3_OPM_MODE_OK(TIM3_OPMode)); /* Set or Reset the OPM Bit */ if (TIM3_OPMode != TIM3_OPMODE_REPETITIVE) { TIM3->CR1 |= TIM3_CR1_OPM; } else { TIM3->CR1 &= (uint8_t)(~TIM3_CR1_OPM); } } /** * @brief Configures the TIM3 Prescaler. * @param Prescaler specifies the Prescaler Register value * This parameter can be one of the following values * - TIM3_PRESCALER_1 * - TIM3_PRESCALER_2 * - TIM3_PRESCALER_4 * - TIM3_PRESCALER_8 * - TIM3_PRESCALER_16 * - TIM3_PRESCALER_32 * - TIM3_PRESCALER_64 * - TIM3_PRESCALER_128 * - TIM3_PRESCALER_256 * - TIM3_PRESCALER_512 * - TIM3_PRESCALER_1024 * - TIM3_PRESCALER_2048 * - TIM3_PRESCALER_4096 * - TIM3_PRESCALER_8192 * - TIM3_PRESCALER_16384 * - TIM3_PRESCALER_32768 * @param TIM3_PSCReloadMode specifies the TIM3 Prescaler Reload mode. * This parameter can be one of the following values * - TIM3_PSCRELOADMODE_IMMEDIATE: The Prescaler is loaded * immediately. * - TIM3_PSCRELOADMODE_UPDATE: The Prescaler is loaded at * the update event. * @retval None */ void TIM3_PrescalerConfig(TIM3_Prescaler_TypeDef Prescaler, TIM3_PSCReloadMode_TypeDef TIM3_PSCReloadMode) { /* Check the parameters */ assert_param(IS_TIM3_PRESCALER_RELOAD_OK(TIM3_PSCReloadMode)); assert_param(IS_TIM3_PRESCALER_OK(Prescaler)); /* Set the Prescaler value */ TIM3->PSCR = (uint8_t)Prescaler; /* Set or reset the UG Bit */ TIM3->EGR = (uint8_t)TIM3_PSCReloadMode; } /** * @brief Forces the TIM3 Channel1 output waveform to active or inactive level. * @param TIM3_ForcedAction specifies the forced Action to be set to the output waveform. * This parameter can be one of the following values: * - TIM3_FORCEDACTION_ACTIVE: Force active level on OC1REF * - TIM3_FORCEDACTION_INACTIVE: Force inactive level on * OC1REF. * @retval None */ void TIM3_ForcedOC1Config(TIM3_ForcedAction_TypeDef TIM3_ForcedAction) { /* Check the parameters */ assert_param(IS_TIM3_FORCED_ACTION_OK(TIM3_ForcedAction)); /* Reset the OCM Bits & Configure the Forced output Mode */ TIM3->CCMR1 = (uint8_t)((uint8_t)(TIM3->CCMR1 & (uint8_t)(~TIM3_CCMR_OCM)) | (uint8_t)TIM3_ForcedAction); } /** * @brief Forces the TIM3 Channel2 output waveform to active or inactive level. * @param TIM3_ForcedAction specifies the forced Action to be set to the output waveform. * This parameter can be one of the following values: * - TIM3_FORCEDACTION_ACTIVE: Force active level on OC2REF * - TIM3_FORCEDACTION_INACTIVE: Force inactive level on * OC2REF. * @retval None */ void TIM3_ForcedOC2Config(TIM3_ForcedAction_TypeDef TIM3_ForcedAction) { /* Check the parameters */ assert_param(IS_TIM3_FORCED_ACTION_OK(TIM3_ForcedAction)); /* Reset the OCM Bits & Configure the Forced output Mode */ TIM3->CCMR2 = (uint8_t)((uint8_t)(TIM3->CCMR2 & (uint8_t)(~TIM3_CCMR_OCM)) | (uint8_t)TIM3_ForcedAction); } /** * @brief Enables or disables TIM3 peripheral Preload register on ARR. * @param NewState new state of the TIM3 peripheral Preload register. * This parameter can be ENABLE or DISABLE. * @retval None */ void TIM3_ARRPreloadConfig(FunctionalState NewState) { /* Check the parameters */ assert_param(IS_FUNCTIONALSTATE_OK(NewState)); /* Set or Reset the ARPE Bit */ if (NewState != DISABLE) { TIM3->CR1 |= TIM3_CR1_ARPE; } else { TIM3->CR1 &= (uint8_t)(~TIM3_CR1_ARPE); } } /** * @brief Enables or disables the TIM3 peripheral Preload Register on CCR1. * @param NewState new state of the Capture Compare Preload register. * This parameter can be ENABLE or DISABLE. * @retval None */ void TIM3_OC1PreloadConfig(FunctionalState NewState) { /* Check the parameters */ assert_param(IS_FUNCTIONALSTATE_OK(NewState)); /* Set or Reset the OC1PE Bit */ if (NewState != DISABLE) { TIM3->CCMR1 |= TIM3_CCMR_OCxPE; } else { TIM3->CCMR1 &= (uint8_t)(~TIM3_CCMR_OCxPE); } } /** * @brief Enables or disables the TIM3 peripheral Preload Register on CCR2. * @param NewState new state of the Capture Compare Preload register. * This parameter can be ENABLE or DISABLE. * @retval None */ void TIM3_OC2PreloadConfig(FunctionalState NewState) { /* Check the parameters */ assert_param(IS_FUNCTIONALSTATE_OK(NewState)); /* Set or Reset the OC2PE Bit */ if (NewState != DISABLE) { TIM3->CCMR2 |= TIM3_CCMR_OCxPE; } else { TIM3->CCMR2 &= (uint8_t)(~TIM3_CCMR_OCxPE); } } /** * @brief Configures the TIM3 event to be generated by software. * @param TIM3_EventSource specifies the event source. * This parameter can be one of the following values: * - TIM3_EVENTSOURCE_UPDATE: TIM3 update Event source * - TIM3_EVENTSOURCE_CC1: TIM3 Capture Compare 1 Event source * - TIM3_EVENTSOURCE_CC2: TIM3 Capture Compare 2 Event source * @retval None */ void TIM3_GenerateEvent(TIM3_EventSource_TypeDef TIM3_EventSource) { /* Check the parameters */ assert_param(IS_TIM3_EVENT_SOURCE_OK(TIM3_EventSource)); /* Set the event sources */ TIM3->EGR = (uint8_t)TIM3_EventSource; } /** * @brief Configures the TIM3 Channel 1 polarity. * @param TIM3_OCPolarity specifies the OC1 Polarity. * This parameter can be one of the following values: * - TIM3_OCPOLARITY_LOW: Output Compare active low * - TIM3_OCPOLARITY_HIGH: Output Compare active high * @retval None */ void TIM3_OC1PolarityConfig(TIM3_OCPolarity_TypeDef TIM3_OCPolarity) { /* Check the parameters */ assert_param(IS_TIM3_OC_POLARITY_OK(TIM3_OCPolarity)); /* Set or Reset the CC1P Bit */ if (TIM3_OCPolarity != TIM3_OCPOLARITY_HIGH) { TIM3->CCER1 |= TIM3_CCER1_CC1P; } else { TIM3->CCER1 &= (uint8_t)(~TIM3_CCER1_CC1P); } } /** * @brief Configures the TIM3 Channel 2 polarity. * @param TIM3_OCPolarity specifies the OC2 Polarity. * This parameter can be one of the following values: * - TIM3_OCPOLARITY_LOW: Output Compare active low * - TIM3_OCPOLARITY_HIGH: Output Compare active high * @retval None */ void TIM3_OC2PolarityConfig(TIM3_OCPolarity_TypeDef TIM3_OCPolarity) { /* Check the parameters */ assert_param(IS_TIM3_OC_POLARITY_OK(TIM3_OCPolarity)); /* Set or Reset the CC2P Bit */ if (TIM3_OCPolarity != TIM3_OCPOLARITY_HIGH) { TIM3->CCER1 |= TIM3_CCER1_CC2P; } else { TIM3->CCER1 &= (uint8_t)(~TIM3_CCER1_CC2P); } } /** * @brief Enables or disables the TIM3 Capture Compare Channel x. * @param TIM3_Channel specifies the TIM3 Channel. * This parameter can be one of the following values: * - TIM3_CHANNEL_1: TIM3 Channel1 * - TIM3_CHANNEL_2: TIM3 Channel2 * @param NewState specifies the TIM3 Channel CCxE bit new state. * This parameter can be: ENABLE or DISABLE. * @retval None */ void TIM3_CCxCmd(TIM3_Channel_TypeDef TIM3_Channel, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_TIM3_CHANNEL_OK(TIM3_Channel)); assert_param(IS_FUNCTIONALSTATE_OK(NewState)); if (TIM3_Channel == TIM3_CHANNEL_1) { /* Set or Reset the CC1E Bit */ if (NewState != DISABLE) { TIM3->CCER1 |= TIM3_CCER1_CC1E; } else { TIM3->CCER1 &= (uint8_t)(~TIM3_CCER1_CC1E); } } else { /* Set or Reset the CC2E Bit */ if (NewState != DISABLE) { TIM3->CCER1 |= TIM3_CCER1_CC2E; } else { TIM3->CCER1 &= (uint8_t)(~TIM3_CCER1_CC2E); } } } /** * @brief Selects the TIM3 Output Compare Mode. This function disables the * selected channel before changing the Output Compare Mode. User has to * enable this channel using TIM3_CCxCmd and TIM3_CCxNCmd functions. * @param TIM3_Channel specifies the TIM3 Channel. * This parameter can be one of the following values: * - TIM3_CHANNEL_1: TIM3 Channel1 * - TIM3_CHANNEL_2: TIM3 Channel2 * @param TIM3_OCMode specifies the TIM3 Output Compare Mode. * This parameter can be one of the following values: * - TIM3_OCMODE_TIMING * - TIM3_OCMODE_ACTIVE * - TIM3_OCMODE_TOGGLE * - TIM3_OCMODE_PWM1 * - TIM3_OCMODE_PWM2 * - TIM3_FORCEDACTION_ACTIVE * - TIM3_FORCEDACTION_INACTIVE * @retval None */ void TIM3_SelectOCxM(TIM3_Channel_TypeDef TIM3_Channel, TIM3_OCMode_TypeDef TIM3_OCMode) { /* Check the parameters */ assert_param(IS_TIM3_CHANNEL_OK(TIM3_Channel)); assert_param(IS_TIM3_OCM_OK(TIM3_OCMode)); if (TIM3_Channel == TIM3_CHANNEL_1) { /* Disable the Channel 1: Reset the CCE Bit */ TIM3->CCER1 &= (uint8_t)(~TIM3_CCER1_CC1E); /* Reset the Output Compare Bits & Set the Output Compare Mode */ TIM3->CCMR1 = (uint8_t)((uint8_t)(TIM3->CCMR1 & (uint8_t)(~TIM3_CCMR_OCM)) | (uint8_t)TIM3_OCMode); } else { /* Disable the Channel 2: Reset the CCE Bit */ TIM3->CCER1 &= (uint8_t)(~TIM3_CCER1_CC2E); /* Reset the Output Compare Bits & Set the Output Compare Mode */ TIM3->CCMR2 = (uint8_t)((uint8_t)(TIM3->CCMR2 & (uint8_t)(~TIM3_CCMR_OCM)) | (uint8_t)TIM3_OCMode); } } /** * @brief Sets the TIM3 Counter Register value. * @param Counter specifies the Counter register new value. * This parameter is between 0x0000 and 0xFFFF. * @retval None */ void TIM3_SetCounter(uint16_t Counter) { /* Set the Counter Register value */ TIM3->CNTRH = (uint8_t)(Counter >> 8); TIM3->CNTRL = (uint8_t)(Counter); } /** * @brief Sets the TIM3 Autoreload Register value. * @param Autoreload specifies the Autoreload register new value. * This parameter is between 0x0000 and 0xFFFF. * @retval None */ void TIM3_SetAutoreload(uint16_t Autoreload) { /* Set the Autoreload Register value */ TIM3->ARRH = (uint8_t)(Autoreload >> 8); TIM3->ARRL = (uint8_t)(Autoreload); } /** * @brief Sets the TIM3 Capture Compare1 Register value. * @param Compare1 specifies the Capture Compare1 register new value. * This parameter is between 0x0000 and 0xFFFF. * @retval None */ void TIM3_SetCompare1(uint16_t Compare1) { /* Set the Capture Compare1 Register value */ TIM3->CCR1H = (uint8_t)(Compare1 >> 8); TIM3->CCR1L = (uint8_t)(Compare1); } /** * @brief Sets the TIM3 Capture Compare2 Register value. * @param Compare2 specifies the Capture Compare2 register new value. * This parameter is between 0x0000 and 0xFFFF. * @retval None */ void TIM3_SetCompare2(uint16_t Compare2) { /* Set the Capture Compare2 Register value */ TIM3->CCR2H = (uint8_t)(Compare2 >> 8); TIM3->CCR2L = (uint8_t)(Compare2); } /** * @brief Sets the TIM3 Input Capture 1 prescaler. * @param TIM3_IC1Prescaler specifies the Input Capture prescaler new value * This parameter can be one of the following values: * - TIM3_ICPSC_DIV1: no prescaler * - TIM3_ICPSC_DIV2: capture is done once every 2 events * - TIM3_ICPSC_DIV4: capture is done once every 4 events * - TIM3_ICPSC_DIV8: capture is done once every 8 events * @retval None */ void TIM3_SetIC1Prescaler(TIM3_ICPSC_TypeDef TIM3_IC1Prescaler) { /* Check the parameters */ assert_param(IS_TIM3_IC_PRESCALER_OK(TIM3_IC1Prescaler)); /* Reset the IC1PSC Bits & Set the IC1PSC value */ TIM3->CCMR1 = (uint8_t)((uint8_t)(TIM3->CCMR1 & (uint8_t)(~TIM3_CCMR_ICxPSC)) | (uint8_t)TIM3_IC1Prescaler); } /** * @brief Sets the TIM3 Input Capture 2 prescaler. * @param TIM3_IC2Prescaler specifies the Input Capture prescaler new value * This parameter can be one of the following values: * - TIM3_ICPSC_DIV1: no prescaler * - TIM3_ICPSC_DIV2: capture is done once every 2 events * - TIM3_ICPSC_DIV4: capture is done once every 4 events * - TIM3_ICPSC_DIV8: capture is done once every 8 events * @retval None */ void TIM3_SetIC2Prescaler(TIM3_ICPSC_TypeDef TIM3_IC2Prescaler) { /* Check the parameters */ assert_param(IS_TIM3_IC_PRESCALER_OK(TIM3_IC2Prescaler)); /* Reset the IC1PSC Bits & Set the IC1PSC value */ TIM3->CCMR2 = (uint8_t)((uint8_t)(TIM3->CCMR2 & (uint8_t)(~TIM3_CCMR_ICxPSC)) | (uint8_t)TIM3_IC2Prescaler); } /** * @brief Gets the TIM3 Input Capture 1 value. * @param None * @retval Capture Compare 1 Register value. */ uint16_t TIM3_GetCapture1(void) { /* Get the Capture 1 Register value */ uint16_t tmpccr1 = 0; uint8_t tmpccr1l=0, tmpccr1h=0; tmpccr1h = TIM3->CCR1H; tmpccr1l = TIM3->CCR1L; tmpccr1 = (uint16_t)(tmpccr1l); tmpccr1 |= (uint16_t)((uint16_t)tmpccr1h << 8); /* Get the Capture 1 Register value */ return (uint16_t)tmpccr1; } /** * @brief Gets the TIM3 Input Capture 2 value. * @param None * @retval Capture Compare 2 Register value. */ uint16_t TIM3_GetCapture2(void) { /* Get the Capture 2 Register value */ uint16_t tmpccr2 = 0; uint8_t tmpccr2l=0, tmpccr2h=0; tmpccr2h = TIM3->CCR2H; tmpccr2l = TIM3->CCR2L; tmpccr2 = (uint16_t)(tmpccr2l); tmpccr2 |= (uint16_t)((uint16_t)tmpccr2h << 8); /* Get the Capture 2 Register value */ return (uint16_t)tmpccr2; } /** * @brief Gets the TIM3 Counter value. * @param None * @retval Counter Register value. */ uint16_t TIM3_GetCounter(void) { uint16_t tmpcntr = 0; tmpcntr = ((uint16_t)TIM3->CNTRH << 8); /* Get the Counter Register value */ return (uint16_t)( tmpcntr| (uint16_t)(TIM3->CNTRL)); } /** * @brief Gets the TIM3 Prescaler value. * @param None * @retval Prescaler Register configuration value @ref TIM3_Prescaler_TypeDef. */ TIM3_Prescaler_TypeDef TIM3_GetPrescaler(void) { /* Get the Prescaler Register value */ return (TIM3_Prescaler_TypeDef)(TIM3->PSCR); } /** * @brief Checks whether the specified TIM3 flag is set or not. * @param TIM3_FLAG specifies the flag to check. * This parameter can be one of the following values: * - TIM3_FLAG_UPDATE: TIM3 update Flag * - TIM3_FLAG_CC1: TIM3 Capture Compare 1 Flag * - TIM3_FLAG_CC2: TIM3 Capture Compare 2 Flag * - TIM3_FLAG_CC1OF: TIM3 Capture Compare 1 over capture Flag * - TIM3_FLAG_CC2OF: TIM3 Capture Compare 2 over capture Flag * @retval FlagStatus The new state of TIM3_FLAG (SET or RESET). */ FlagStatus TIM3_GetFlagStatus(TIM3_FLAG_TypeDef TIM3_FLAG) { FlagStatus bitstatus = RESET; uint8_t tim3_flag_l = 0, tim3_flag_h = 0; /* Check the parameters */ assert_param(IS_TIM3_GET_FLAG_OK(TIM3_FLAG)); tim3_flag_l = (uint8_t)(TIM3->SR1 & (uint8_t)TIM3_FLAG); tim3_flag_h = (uint8_t)((uint16_t)TIM3_FLAG >> 8); if (((tim3_flag_l) | (uint8_t)(TIM3->SR2 & tim3_flag_h)) != (uint8_t)RESET ) { bitstatus = SET; } else { bitstatus = RESET; } return (FlagStatus)bitstatus; } /** * @brief Clears the TIM3’s pending flags. * @param TIM3_FLAG specifies the flag to clear. * This parameter can be one of the following values: * - TIM3_FLAG_UPDATE: TIM3 update Flag * - TIM3_FLAG_CC1: TIM3 Capture Compare 1 Flag * - TIM3_FLAG_CC2: TIM3 Capture Compare 2 Flag * - TIM3_FLAG_CC1OF: TIM3 Capture Compare 1 over capture Flag * - TIM3_FLAG_CC2OF: TIM3 Capture Compare 2 over capture Flag * @retval None. */ void TIM3_ClearFlag(TIM3_FLAG_TypeDef TIM3_FLAG) { /* Check the parameters */ assert_param(IS_TIM3_CLEAR_FLAG_OK(TIM3_FLAG)); /* Clear the flags (rc_w0) clear this bit by writing 0. Writing ‘1’ has no effect*/ TIM3->SR1 = (uint8_t)(~((uint8_t)(TIM3_FLAG))); TIM3->SR2 = (uint8_t)(~((uint8_t)((uint16_t)TIM3_FLAG >> 8))); } /** * @brief Checks whether the TIM3 interrupt has occurred or not. * @param TIM3_IT specifies the TIM3 interrupt source to check. * This parameter can be one of the following values: * - TIM3_IT_UPDATE: TIM3 update Interrupt source * - TIM3_IT_CC1: TIM3 Capture Compare 1 Interrupt source * - TIM3_IT_CC2: TIM3 Capture Compare 2 Interrupt source * @retval ITStatus The new state of the TIM3_IT(SET or RESET). */ ITStatus TIM3_GetITStatus(TIM3_IT_TypeDef TIM3_IT) { ITStatus bitstatus = RESET; uint8_t TIM3_itStatus = 0, TIM3_itEnable = 0; /* Check the parameters */ assert_param(IS_TIM3_GET_IT_OK(TIM3_IT)); TIM3_itStatus = (uint8_t)(TIM3->SR1 & TIM3_IT); TIM3_itEnable = (uint8_t)(TIM3->IER & TIM3_IT); if ((TIM3_itStatus != (uint8_t)RESET ) && (TIM3_itEnable != (uint8_t)RESET )) { bitstatus = SET; } else { bitstatus = RESET; } return (ITStatus)(bitstatus); } /** * @brief Clears the TIM3's interrupt pending bits. * @param TIM3_IT specifies the pending bit to clear. * This parameter can be one of the following values: * - TIM3_IT_UPDATE: TIM3 update Interrupt source * - TIM3_IT_CC1: TIM3 Capture Compare 1 Interrupt source * - TIM3_IT_CC2: TIM3 Capture Compare 2 Interrupt source * @retval None. */ void TIM3_ClearITPendingBit(TIM3_IT_TypeDef TIM3_IT) { /* Check the parameters */ assert_param(IS_TIM3_IT_OK(TIM3_IT)); /* Clear the IT pending Bit */ TIM3->SR1 = (uint8_t)(~TIM3_IT); } /** * @brief Configure the TI1 as Input. * @param TIM3_ICPolarity The Input Polarity. * This parameter can be one of the following values: * - TIM3_ICPOLARITY_FALLING * - TIM3_ICPOLARITY_RISING * @param TIM3_ICSelection specifies the input to be used. * This parameter can be one of the following values: * - TIM3_ICSELECTION_DIRECTTI: TIM3 Input 1 is selected to * be connected to IC1. * - TIM3_ICSELECTION_INDIRECTTI: TIM3 Input 1 is selected to * be connected to IC2. * @param TIM3_ICFilter Specifies the Input Capture Filter. * This parameter must be a value between 0x00 and 0x0F. * @retval None */ static void TI1_Config(uint8_t TIM3_ICPolarity, uint8_t TIM3_ICSelection, uint8_t TIM3_ICFilter) { /* Disable the Channel 1: Reset the CCE Bit */ TIM3->CCER1 &= (uint8_t)(~TIM3_CCER1_CC1E); /* Select the Input and set the filter */ TIM3->CCMR1 = (uint8_t)((uint8_t)(TIM3->CCMR1 & (uint8_t)(~( TIM3_CCMR_CCxS | TIM3_CCMR_ICxF))) | (uint8_t)(( (TIM3_ICSelection)) | ((uint8_t)( TIM3_ICFilter << 4)))); /* Select the Polarity */ if (TIM3_ICPolarity != TIM3_ICPOLARITY_RISING) { TIM3->CCER1 |= TIM3_CCER1_CC1P; } else { TIM3->CCER1 &= (uint8_t)(~TIM3_CCER1_CC1P); } /* Set the CCE Bit */ TIM3->CCER1 |= TIM3_CCER1_CC1E; } /** * @brief Configure the TI2 as Input. * @param TIM3_ICPolarity The Input Polarity. * This parameter can be one of the following values: * - TIM3_ICPOLARITY_FALLING * - TIM3_ICPOLARITY_RISING * @param TIM3_ICSelection specifies the input to be used. * This parameter can be one of the following values: * - TIM3_ICSELECTION_DIRECTTI: TIM3 Input 2 is selected to * be connected to IC2. * - TIM3_ICSELECTION_INDIRECTTI: TIM3 Input 2 is selected to * be connected to IC1. * @param TIM3_ICFilter Specifies the Input Capture Filter. * This parameter must be a value between 0x00 and 0x0F. * @retval None */ static void TI2_Config(uint8_t TIM3_ICPolarity, uint8_t TIM3_ICSelection, uint8_t TIM3_ICFilter) { /* Disable the Channel 2: Reset the CCE Bit */ TIM3->CCER1 &= (uint8_t)(~TIM3_CCER1_CC2E); /* Select the Input and set the filter */ TIM3->CCMR2 = (uint8_t)((uint8_t)(TIM3->CCMR2 & (uint8_t)(~( TIM3_CCMR_CCxS | TIM3_CCMR_ICxF ))) | (uint8_t)(( (TIM3_ICSelection)) | ((uint8_t)( TIM3_ICFilter << 4)))); /* Select the Polarity */ if (TIM3_ICPolarity != TIM3_ICPOLARITY_RISING) { TIM3->CCER1 |= TIM3_CCER1_CC2P; } else { TIM3->CCER1 &= (uint8_t)(~TIM3_CCER1_CC2P); } /* Set the CCE Bit */ TIM3->CCER1 |= TIM3_CCER1_CC2E; } /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
SeanGau/Arduino_Core_STM8
cores/arduino/board.c
#include "board.h" #ifdef __cplusplus extern "C" { #endif void __libc_init_array(void); void init(void) { hw_config_init(); } #ifdef __cplusplus } #endif
SeanGau/Arduino_Core_STM8
cores/arduino/stm8/PinNames.h
#ifndef _PINNAMES_H #define _PINNAMES_H #include "PinNamesTypes.h" #include "PortNames.h" #ifdef __cplusplus extern "C" { #endif typedef enum { PA_0 = (PortA << 4) + 0x00, PA_1 = (PortA << 4) + 0x01, PA_2 = (PortA << 4) + 0x02, PA_3 = (PortA << 4) + 0x03, PA_4 = (PortA << 4) + 0x04, PA_5 = (PortA << 4) + 0x05, PA_6 = (PortA << 4) + 0x06, PA_7 = (PortA << 4) + 0x07, PB_0 = (PortB << 4) + 0x00, PB_1 = (PortB << 4) + 0x01, PB_2 = (PortB << 4) + 0x02, PB_3 = (PortB << 4) + 0x03, PB_4 = (PortB << 4) + 0x04, PB_5 = (PortB << 4) + 0x05, PB_6 = (PortB << 4) + 0x06, PB_7 = (PortB << 4) + 0x07, #if defined (GPIOC_BaseAddress) || defined(GPIOC_BASE) PC_0 = (PortC << 4) + 0x00, PC_1 = (PortC << 4) + 0x01, PC_2 = (PortC << 4) + 0x02, PC_3 = (PortC << 4) + 0x03, PC_4 = (PortC << 4) + 0x04, PC_5 = (PortC << 4) + 0x05, PC_6 = (PortC << 4) + 0x06, PC_7 = (PortC << 4) + 0x07, #endif #if defined GPIOD_BaseAddress || defined(GPIOD_BASE) PD_0 = (PortD << 4) + 0x00, PD_1 = (PortD << 4) + 0x01, PD_2 = (PortD << 4) + 0x02, PD_3 = (PortD << 4) + 0x03, PD_4 = (PortD << 4) + 0x04, PD_5 = (PortD << 4) + 0x05, PD_6 = (PortD << 4) + 0x06, PD_7 = (PortD << 4) + 0x07, #endif #if defined GPIOE_BaseAddress || defined(GPIOE_BASE) PE_0 = (PortE << 4) + 0x00, PE_1 = (PortE << 4) + 0x01, PE_2 = (PortE << 4) + 0x02, PE_3 = (PortE << 4) + 0x03, PE_4 = (PortE << 4) + 0x04, PE_5 = (PortE << 4) + 0x05, PE_6 = (PortE << 4) + 0x06, PE_7 = (PortE << 4) + 0x07, #endif #if defined GPIOF_BaseAddress || defined(GPIOF_BASE) PF_0 = (PortF << 4) + 0x00, PF_1 = (PortF << 4) + 0x01, PF_2 = (PortF << 4) + 0x02, PF_3 = (PortF << 4) + 0x03, PF_4 = (PortF << 4) + 0x04, PF_5 = (PortF << 4) + 0x05, PF_6 = (PortF << 4) + 0x06, PF_7 = (PortF << 4) + 0x07, #endif #if defined GPIOG_BaseAddress || defined(GPIOG_BASE) PG_0 = (PortG << 4) + 0x00, PG_1 = (PortG << 4) + 0x01, PG_2 = (PortG << 4) + 0x02, PG_3 = (PortG << 4) + 0x03, PG_4 = (PortG << 4) + 0x04, PG_5 = (PortG << 4) + 0x05, PG_6 = (PortG << 4) + 0x06, PG_7 = (PortG << 4) + 0x07, #endif #if defined GPIOH_BaseAddress || defined(GPIOH_BASE) PH_0 = (PortH << 4) + 0x00, PH_1 = (PortH << 4) + 0x01, PH_2 = (PortH << 4) + 0x02, PH_3 = (PortH << 4) + 0x03, PH_4 = (PortH << 4) + 0x04, PH_5 = (PortH << 4) + 0x05, PH_6 = (PortH << 4) + 0x06, PH_7 = (PortH << 4) + 0x07, #endif #if defined GPIOI_BaseAddress || defined(GPIOI_BASE) PI_0 = (PortI << 4) + 0x00, #endif //NOT connecter NC = (int)0xFF } PinName; #ifdef __cplusplus } #endif #endif
SeanGau/Arduino_Core_STM8
system/Drivers/STM8Sxx_StdPeriph_Driver/src/stm8s_can.c
<filename>system/Drivers/STM8Sxx_StdPeriph_Driver/src/stm8s_can.c /** ****************************************************************************** * @file stm8s_can.c * @author MCD Application Team * @version V2.3.0 * @date 16-June-2017 * @brief This file contains all the functions for the CAN peripheral. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT 2014 STMicroelectronics</center></h2> * * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License"); * You may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.st.com/software_license_agreement_liberty_v2 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm8s_can.h" /** @addtogroup STM8S_StdPeriph_Driver * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ #define CAN_IDLIST_IDMASK_MASK ((uint8_t) 0x55) #define CAN_IDMASK_IDLIST_MASK ((uint8_t) 0xAA) #define CAN_MODE_MASK ((uint8_t) 0x03) #define CAN_ACKNOWLEDGE_TIMEOUT ((uint16_t)0xFFFF) /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ __IO uint32_t _Id = 0; __IO uint8_t _IDE = 0; __IO uint8_t _RTR = 0; __IO uint8_t _DLC = 0; __IO uint8_t _Data[8] = {0}; __IO uint8_t _FMI = 0; /* Private function prototypes -----------------------------------------------*/ static ITStatus CheckITStatus(uint8_t CAN_Reg, uint8_t It_Bit); /* Private functions ---------------------------------------------------------*/ /** * @addtogroup CAN_Public_Functions * @{ */ /** * @brief Deinitializes the CAN peripheral registers to their default reset values. * @param None * @retval None */ void CAN_DeInit(void) { /* Request initialisation */ CAN->MCR = CAN_MCR_INRQ; CAN->PSR = CAN_Page_Config; CAN_OperatingModeRequest(CAN_OperatingMode_Initialization); CAN->Page.Config.ESR = CAN_ESR_RESET_VALUE; CAN->Page.Config.EIER = CAN_EIER_RESET_VALUE; CAN->Page.Config.BTR1 = CAN_BTR1_RESET_VALUE; CAN->Page.Config.BTR2 = CAN_BTR2_RESET_VALUE; CAN->Page.Config.FMR1 = CAN_FMR1_RESET_VALUE; CAN->Page.Config.FMR2 = CAN_FMR2_RESET_VALUE; CAN->Page.Config.FCR1 = CAN_FCR_RESET_VALUE; CAN->Page.Config.FCR2 = CAN_FCR_RESET_VALUE; CAN->Page.Config.FCR3 = CAN_FCR_RESET_VALUE; CAN_OperatingModeRequest(CAN_OperatingMode_Normal); CAN->PSR = CAN_Page_RxFifo; CAN->Page.RxFIFO.MDLCR = CAN_MDLC_RESET_VALUE; CAN->PSR = CAN_Page_TxMailBox0; CAN->Page.TxMailbox.MDLCR = CAN_MDLC_RESET_VALUE; CAN->PSR = CAN_Page_TxMailBox1; CAN->Page.TxMailbox.MDLCR = CAN_MDLC_RESET_VALUE; CAN->PSR = CAN_Page_TxMailBox2; CAN->Page.TxMailbox.MDLCR = CAN_MDLC_RESET_VALUE; CAN->MCR = CAN_MCR_RESET_VALUE; CAN->MSR = (uint8_t)(~CAN_MSR_RESET_VALUE);/* rc_w1 */ CAN->TSR = (uint8_t)(~CAN_TSR_RESET_VALUE);/* rc_w1 */ CAN->RFR = (uint8_t)(~CAN_RFR_RESET_VALUE);/* rc_w1 */ CAN->IER = CAN_IER_RESET_VALUE; CAN->DGR = CAN_DGR_RESET_VALUE; CAN->PSR = CAN_PSR_RESET_VALUE; } /** * @brief Initializes the CAN peripheral according to the specified parameters. * @param CAN_MasterCtrl : Master control option, can be one or a combination of @ref CAN_MasterCtrl_TypeDef. * @param CAN_Mode : CAN mode , can be one of @ref CAN_Mode_TypeDef. * @param CAN_SynJumpWidth : CAN Synchronisation Jump Width , can be one of @ref CAN_SynJumpWidth_TypeDef. * @param CAN_BitSeg1 : CAN bit segment 1 , can be one of @ref CAN_BitSeg1_TypeDef. * @param CAN_BitSeg2 : CAN bit segment 2 , can be one of @ref CAN_BitSeg2_TypeDef. * @param CAN_Prescaler : CAN Baud Rate Prescaler , can be a value from 0x01 to 0xFF. * @retval Indicates if initialization is succeed. it can be one of @ref CAN_InitStatus_TypeDef enumeration. */ CAN_InitStatus_TypeDef CAN_Init(CAN_MasterCtrl_TypeDef CAN_MasterCtrl, CAN_Mode_TypeDef CAN_Mode, CAN_SynJumpWidth_TypeDef CAN_SynJumpWidth, CAN_BitSeg1_TypeDef CAN_BitSeg1, CAN_BitSeg2_TypeDef CAN_BitSeg2, uint8_t CAN_Prescaler) { CAN_InitStatus_TypeDef InitStatus = CAN_InitStatus_Failed; uint16_t timeout = CAN_ACKNOWLEDGE_TIMEOUT; CAN_Page_TypeDef can_page = CAN_GetSelectedPage(); /* Check the parameters */ assert_param(IS_CAN_MASTERCTRL_OK(CAN_MasterCtrl)); assert_param(IS_CAN_MODE_OK(CAN_Mode)); assert_param(IS_CAN_SYNJUMPWIDTH_OK(CAN_SynJumpWidth)); assert_param(IS_CAN_BITSEG1_OK(CAN_BitSeg1)); assert_param(IS_CAN_BITSEG2_OK(CAN_BitSeg2)); assert_param(IS_CAN_PRESCALER_OK(CAN_Prescaler)); /* Request initialisation */ CAN->MCR = CAN_MCR_INRQ; /* Wait the acknowledge */ while (((uint8_t)(CAN->MSR & CAN_MSR_INAK) != 0x01) && ((uint16_t)timeout != 0)) { timeout--; } /* Check acknowledged */ if ((CAN->MSR & CAN_MSR_INAK) != CAN_MSR_INAK) { InitStatus = CAN_InitStatus_Failed; } else { /* Set the time triggered communication mode & Set the automatic bus-off management & Set the automatic wake-up mode & Set the no automatic retransmission & Set the receive FIFO locked mode & Set the transmit FIFO priority */ CAN->MCR |= (uint8_t)CAN_MasterCtrl; /* Set the bit timing register */ CAN->DGR |= (uint8_t)CAN_Mode ; CAN->PSR = CAN_Page_Config; CAN->Page.Config.BTR1 = (uint8_t)((uint8_t)(CAN_Prescaler - (uint8_t)1) | CAN_SynJumpWidth); CAN->Page.Config.BTR2 = (uint8_t)(CAN_BitSeg1 | (uint8_t)CAN_BitSeg2); /* Request leave initialisation */ CAN->MCR &= (uint8_t)(~CAN_MCR_INRQ); /* Wait the acknowledge */ timeout = 0xFFFF; while ((((uint8_t)(CAN->MSR & CAN_MSR_INAK) == 0x01))&&(timeout != 0)) { timeout--; } /* Check acknowledged */ if ((CAN->MSR & CAN_MSR_INAK) == CAN_MSR_INAK) { InitStatus = CAN_InitStatus_Failed; } else { InitStatus = CAN_InitStatus_Success; } } /*Restore Last Page*/ CAN_SelectPage(can_page); /* Return the status of initialization */ return (CAN_InitStatus_TypeDef)InitStatus; } /** * @brief Initializes the CAN peripheral Filter according to the specified parameters. * @param CAN_FilterNumber : CAN Filter number , can be one of @ref CAN_FilterNumber_TypeDef * @param CAN_FilterActivation : CAN Filter Activation state , can be one of @ref FunctionalState * @param CAN_FilterMode : CAN Filter Mode , can be one of @ref CAN_FilterMode_TypeDef * @param CAN_FilterScale : CAN Filter Scale , can be one of @ref CAN_FilterScale_TypeDef * @param CAN_FilterID1 : CAN Filter ID 1 , can be a value from 0x00 to 0xFF * @param CAN_FilterID2 : CAN Filter ID 2 , can be a value from 0x00 to 0xFF * @param CAN_FilterID3 : CAN Filter ID 3 , can be a value from 0x00 to 0xFF * @param CAN_FilterID4 : CAN Filter ID 4 , can be a value from 0x00 to 0xFF * @param CAN_FilterIDMask1 : CAN Filter ID 1/ Mask 1 , can be a value from 0x00 to 0xFF depending of CAN_FilterMode parameter * @param CAN_FilterIDMask2 : CAN Filter ID 2/ Mask 2 , can be a value from 0x00 to 0xFF depending of CAN_FilterMode parameter * @param CAN_FilterIDMask3 : CAN Filter ID 3/ Mask 3 , can be a value from 0x00 to 0xFF depending of CAN_FilterMode parameter * @param CAN_FilterIDMask4 : CAN Filter ID 4/ Mask 4 , can be a value from 0x00 to 0xFF depending of CAN_FilterMode parameter * @retval None */ void CAN_FilterInit(CAN_FilterNumber_TypeDef CAN_FilterNumber, FunctionalState CAN_FilterActivation, CAN_FilterMode_TypeDef CAN_FilterMode, CAN_FilterScale_TypeDef CAN_FilterScale, uint8_t CAN_FilterID1, uint8_t CAN_FilterID2, uint8_t CAN_FilterID3, uint8_t CAN_FilterID4, uint8_t CAN_FilterIDMask1, uint8_t CAN_FilterIDMask2, uint8_t CAN_FilterIDMask3, uint8_t CAN_FilterIDMask4) { uint8_t fact = 0; uint8_t fsc = 0; uint8_t fmhl = 0; CAN_Page_TypeDef can_page_filter = CAN_Page_Filter01; CAN_Page_TypeDef can_page = CAN_GetSelectedPage(); /* Check the parameters */ assert_param(IS_CAN_FILTER_NUMBER_OK(CAN_FilterNumber)); assert_param(IS_FUNCTIONALSTATE_OK(CAN_FilterActivation)); assert_param(IS_CAN_FILTER_MODE_OK(CAN_FilterMode)); assert_param(IS_CAN_FILTER_SCALE_OK(CAN_FilterScale)); if (CAN_FilterNumber == CAN_FilterNumber_0) { fact = 0x01; fsc = 0x00; fmhl = 0x03; can_page_filter = CAN_Page_Filter01; } else if (CAN_FilterNumber == CAN_FilterNumber_1) { fact = 0x10; fsc = 0x04; fmhl = 0x0C; can_page_filter = CAN_Page_Filter01; } else if (CAN_FilterNumber == CAN_FilterNumber_2) { fact = 0x01; fsc = 0x00; fmhl = 0x30; can_page_filter = CAN_Page_Filter23; } else if (CAN_FilterNumber == CAN_FilterNumber_3) { fact = 0x10; fsc = 0x04; fmhl = 0xC0; can_page_filter = CAN_Page_Filter23; } else if (CAN_FilterNumber == CAN_FilterNumber_4) { fact = 0x01; fsc = 0x00; fmhl = 0x03; can_page_filter = CAN_Page_Filter45; } else /*if (CAN_FilterNumber == CAN_FilterNumber_5)*/ { fact = 0x10; fsc = 0x04; fmhl = 0x0C; can_page_filter = CAN_Page_Filter45; } CAN_OperatingModeRequest(CAN_OperatingMode_Initialization); CAN->PSR = CAN_Page_Config; /*---------------------------------------------------------*/ /*Configuration of Filter Scale */ /*---------------------------------------------------------*/ if (can_page_filter == CAN_Page_Filter01) /* FCR1 */ { /* Filter Deactivation & Reset the Filter Scale */ CAN->Page.Config.FCR1 &= (uint8_t)(~(uint8_t)(fact | (uint8_t)((uint8_t)(CAN_FCR1_FSC00|CAN_FCR1_FSC01) << fsc ))); /* Set the new Filter Scale */ CAN->Page.Config.FCR1 |= (uint8_t)(CAN_FilterScale << fsc); } else if (can_page_filter == CAN_Page_Filter23) /* FCR2*/ { /* Filter Deactivation & Reset the Filter Scale */ CAN->Page.Config.FCR2 &= (uint8_t)~(uint8_t)( fact | (uint8_t)((uint8_t)(CAN_FCR1_FSC00|CAN_FCR1_FSC01) << fsc )); /* Set the new Filter Scale */ CAN->Page.Config.FCR2 |= (uint8_t)(CAN_FilterScale << fsc); } else /*if(can_page_filter == CAN_Page_Filter45)*/ /* FCR3*/ { /* Filter Deactivation & Reset the Filter Scale */ CAN->Page.Config.FCR3 &= (uint8_t)~(uint8_t)( fact | (uint8_t)((uint8_t)(CAN_FCR1_FSC00|CAN_FCR1_FSC01) << fsc )); /* Set the new Filter Scale */ CAN->Page.Config.FCR3 |= (uint8_t)(CAN_FilterScale << fsc); } /*---------------------------------------------------------*/ /*Configuration of Filter Mode */ /*---------------------------------------------------------*/ if (can_page_filter != CAN_Page_Filter45) /* FMR1*/ { /* Filter Mode */ if (CAN_FilterMode == CAN_FilterMode_IdMask) { /*Id/Mask mode for the filter*/ CAN->Page.Config.FMR1 &= (uint8_t)~(fmhl); } else if ( CAN_FilterMode == CAN_FilterMode_IdList) { /*Identifier list mode for the filter*/ CAN->Page.Config.FMR1 |= (uint8_t)(fmhl); } else if ( CAN_FilterMode == CAN_FilterMode_IdList_IdMask) { /*Identifier list mode is first for the filter*/ CAN->Page.Config.FMR1 |= (uint8_t)(fmhl & CAN_IDLIST_IDMASK_MASK); } else /* ( CAN_FilterMode == CAN_FilterMode_IdMask_IdList)*/ { /*Id Mask mode is first for the filter*/ CAN->Page.Config.FMR1 |= (uint8_t)(fmhl & CAN_IDMASK_IDLIST_MASK); } } else /* FMR2 */ { /* Filter Mode */ if (CAN_FilterMode == CAN_FilterMode_IdMask) { /*Id/Mask mode for the filter*/ CAN->Page.Config.FMR2 &= (uint8_t)~(fmhl); } else if ( CAN_FilterMode == CAN_FilterMode_IdList) { /*Identifier list mode for the filter*/ CAN->Page.Config.FMR2 |= (uint8_t)(fmhl); } else if ( CAN_FilterMode == CAN_FilterMode_IdList_IdMask) { /*Identifier list mode is first for the filter*/ CAN->Page.Config.FMR2 |= (uint8_t)(fmhl & CAN_IDLIST_IDMASK_MASK); } else /* ( CAN_FilterMode == CAN_FilterMode_IdMask_IdList)*/ { /*Id Mask mode is first for the filter*/ CAN->Page.Config.FMR2 |= (uint8_t)(fmhl & CAN_IDMASK_IDLIST_MASK); } } /*---------------------------------------------------------*/ /*Configuration of Filter IDs */ /*---------------------------------------------------------*/ CAN->PSR = (uint8_t)can_page_filter; if (fsc != 0) { /* Filter Scale */ if (CAN_FilterScale == CAN_FilterScale_8Bit) { CAN->Page.Filter.FR09 = CAN_FilterID1; CAN->Page.Filter.FR10 = CAN_FilterIDMask1; CAN->Page.Filter.FR11 = CAN_FilterID2; CAN->Page.Filter.FR12 = CAN_FilterIDMask2; CAN->Page.Filter.FR13 = CAN_FilterID3; CAN->Page.Filter.FR14 = CAN_FilterIDMask3; CAN->Page.Filter.FR15 = CAN_FilterID4; CAN->Page.Filter.FR16 = CAN_FilterIDMask4; } else if (CAN_FilterScale == CAN_FilterScale_16_8Bit) { CAN->Page.Filter.FR09 = CAN_FilterID1; CAN->Page.Filter.FR10 = CAN_FilterID2; CAN->Page.Filter.FR11 = CAN_FilterIDMask1; CAN->Page.Filter.FR12 = CAN_FilterIDMask2; CAN->Page.Filter.FR13 = CAN_FilterID3; CAN->Page.Filter.FR14 = CAN_FilterIDMask3; CAN->Page.Filter.FR15 = CAN_FilterID4; CAN->Page.Filter.FR16 = CAN_FilterIDMask4; } else if (CAN_FilterScale == CAN_FilterScale_16Bit) { CAN->Page.Filter.FR09 = CAN_FilterID1; CAN->Page.Filter.FR10 = CAN_FilterID2; CAN->Page.Filter.FR11 = CAN_FilterIDMask1; CAN->Page.Filter.FR12 = CAN_FilterIDMask2; CAN->Page.Filter.FR13 = CAN_FilterID3; CAN->Page.Filter.FR14 = CAN_FilterID4; CAN->Page.Filter.FR15 = CAN_FilterIDMask3; CAN->Page.Filter.FR16 = CAN_FilterIDMask4; } else if (CAN_FilterScale == CAN_FilterScale_32Bit) { CAN->Page.Filter.FR09 = CAN_FilterID1; CAN->Page.Filter.FR10 = CAN_FilterID2; CAN->Page.Filter.FR11 = CAN_FilterID3; CAN->Page.Filter.FR12 = CAN_FilterID4; CAN->Page.Filter.FR13 = CAN_FilterIDMask1; CAN->Page.Filter.FR14 = CAN_FilterIDMask2; CAN->Page.Filter.FR15 = CAN_FilterIDMask3; CAN->Page.Filter.FR16 = CAN_FilterIDMask4; } } else { /* Filter Scale */ if (CAN_FilterScale == CAN_FilterScale_8Bit) { CAN->Page.Filter.FR01 = CAN_FilterID1; CAN->Page.Filter.FR02 = CAN_FilterIDMask1; CAN->Page.Filter.FR03 = CAN_FilterID2; CAN->Page.Filter.FR04 = CAN_FilterIDMask2; CAN->Page.Filter.FR05 = CAN_FilterID3; CAN->Page.Filter.FR06 = CAN_FilterIDMask3; CAN->Page.Filter.FR07 = CAN_FilterID4; CAN->Page.Filter.FR08 = CAN_FilterIDMask4; } else if (CAN_FilterScale == CAN_FilterScale_16_8Bit) { CAN->Page.Filter.FR01 = CAN_FilterID1; CAN->Page.Filter.FR02 = CAN_FilterID2; CAN->Page.Filter.FR03 = CAN_FilterIDMask1; CAN->Page.Filter.FR04 = CAN_FilterIDMask2; CAN->Page.Filter.FR05 = CAN_FilterID3; CAN->Page.Filter.FR06 = CAN_FilterIDMask3; CAN->Page.Filter.FR07 = CAN_FilterID4; CAN->Page.Filter.FR08 = CAN_FilterIDMask4; } else if (CAN_FilterScale == CAN_FilterScale_16Bit) { CAN->Page.Filter.FR01 = CAN_FilterID1; CAN->Page.Filter.FR02 = CAN_FilterID2; CAN->Page.Filter.FR03 = CAN_FilterIDMask1; CAN->Page.Filter.FR04 = CAN_FilterIDMask2; CAN->Page.Filter.FR05 = CAN_FilterID3; CAN->Page.Filter.FR06 = CAN_FilterID4; CAN->Page.Filter.FR07 = CAN_FilterIDMask3; CAN->Page.Filter.FR08 = CAN_FilterIDMask4; } else if (CAN_FilterScale == CAN_FilterScale_32Bit) { CAN->Page.Filter.FR01 = CAN_FilterID1; CAN->Page.Filter.FR02 = CAN_FilterID2; CAN->Page.Filter.FR03 = CAN_FilterID3; CAN->Page.Filter.FR04 = CAN_FilterID4; CAN->Page.Filter.FR05 = CAN_FilterIDMask1; CAN->Page.Filter.FR06 = CAN_FilterIDMask2; CAN->Page.Filter.FR07 = CAN_FilterIDMask3; CAN->Page.Filter.FR08 = CAN_FilterIDMask4; } } /*---------------------------------------------------------*/ /*Configuration of Filter Activation */ /*---------------------------------------------------------*/ /* Filter activation */ CAN->PSR = CAN_Page_Config; if (CAN_FilterActivation != DISABLE) { if ((CAN_FilterNumber & 0x06) == 0x00) /* FCR1*/ { CAN->Page.Config.FCR1 |= (uint8_t)fact; } else if ((CAN_FilterNumber & 0x06) == 0x02) /*FCR2*/ { CAN->Page.Config.FCR2 |= (uint8_t)fact; } else /*if((CAN_FilterNumber & 0x06) == 0x04)*/ /*FCR3*/ { CAN->Page.Config.FCR3 |= (uint8_t)fact; } } CAN_OperatingModeRequest(CAN_OperatingMode_Normal); /*Restore Last Page*/ CAN_SelectPage(can_page); } /** * @brief Enables or disables the specified CAN interrupts. * @param CAN_IT: specifies the CAN interrupt sources to be enabled or disabled. * @param NewState : CAN_IT new state , can be one of @ref FunctionalState * @retval None */ void CAN_ITConfig(CAN_IT_TypeDef CAN_IT, FunctionalState NewState) { uint8_t tmperrorinterrupt = 0; CAN_Page_TypeDef can_page = CAN_GetSelectedPage(); /* Check the parameters */ assert_param(IS_CAN_IT_CONFIG_OK(CAN_IT)); assert_param(IS_FUNCTIONALSTATE_OK(NewState)); tmperrorinterrupt = (uint8_t)(((uint16_t)CAN_IT) >>7); tmperrorinterrupt = (uint8_t)((uint8_t)((uint16_t)tmperrorinterrupt & 0xF0) | (uint8_t)((uint8_t)((uint16_t)tmperrorinterrupt & 0x0F) >>1)); CAN->PSR = CAN_Page_Config; if (NewState != DISABLE) { /* Enable the selected CAN interrupt */ CAN->IER |= (uint8_t)(CAN_IT); CAN->Page.Config.EIER |= (uint8_t)(tmperrorinterrupt); } else { /* Disable the selected CAN interrupt */ CAN->IER &= (uint8_t)~(uint8_t)((uint16_t)CAN_IT); CAN->Page.Config.EIER &= (uint8_t)~(tmperrorinterrupt); } /*Restore Last Page*/ CAN_SelectPage(can_page); } /** * @brief Enables or Disables the ST7 CAN Compatibility. * if the ST7 compatibility is Enabled, CAN provides only 2 mailboxes. * if the ST7 compatibility is Disabled, CAN provides 3 mailboxes. * @param CAN_ST7Compatibility : CAN ST7 Compatibility , this parameter can be one of @ref CAN_ST7Compatibility_TypeDef enumeration. * @retval None */ void CAN_ST7CompatibilityCmd(CAN_ST7Compatibility_TypeDef CAN_ST7Compatibility) { /* Check the parameters */ assert_param(IS_CAN_ST7_COMPATIBILITY_OK(CAN_ST7Compatibility)); /*Reset the old configuration of TXM2E */ CAN->DGR &= (uint8_t)(~CAN_DGR_TXM2E); /*Set the old configuration of TXM2E */ CAN->DGR |= (uint8_t)CAN_ST7Compatibility; } /** * @brief Enables or disables the CAN Time TriggerOperation communication mode. * @param NewState : Mode new state , can be one of @ref FunctionalState * @retval None */ void CAN_TTComModeCmd(FunctionalState NewState) { CAN_Page_TypeDef can_page = CAN_GetSelectedPage(); /* Check the parameters */ assert_param(IS_FUNCTIONALSTATE_OK(NewState)); if (NewState != DISABLE) { /*Enable the TTCM mode */ CAN->MCR |= CAN_MCR_TTCM; /*Set TGT bits setting in Tx and FIFO pages*/ CAN->PSR = CAN_Page_TxMailBox0; CAN->Page.TxMailbox.MDLCR |= CAN_MDLCR_TGT; CAN->PSR = CAN_Page_TxMailBox1; CAN->Page.TxMailbox.MDLCR |= CAN_MDLCR_TGT; CAN->PSR = CAN_Page_TxMailBox2; CAN->Page.TxMailbox.MDLCR |= CAN_MDLCR_TGT; CAN->PSR = CAN_Page_RxFifo; CAN->Page.RxFIFO.MDLCR |= CAN_MDLCR_TGT; } else { /*Disable the TTCM mode */ CAN->MCR &= ((uint8_t)~CAN_MCR_TTCM); /*Reset TGT bits setting in Tx and FIFO pages*/ CAN->PSR = CAN_Page_TxMailBox0; CAN->Page.TxMailbox.MDLCR &= ((uint8_t)~CAN_MDLCR_TGT); CAN->PSR = CAN_Page_TxMailBox1; CAN->Page.TxMailbox.MDLCR &= ((uint8_t)~CAN_MDLCR_TGT); CAN->PSR = CAN_Page_TxMailBox2; CAN->Page.TxMailbox.MDLCR &= ((uint8_t)~CAN_MDLCR_TGT); CAN->PSR = CAN_Page_RxFifo; CAN->Page.RxFIFO.MDLCR &= ((uint8_t)~CAN_MDLCR_TGT); } /*Restore Last Page*/ CAN_SelectPage(can_page); } /** * @brief Initiates the transmission of a message. * @param CAN_Id the ID number of the message, its size depends on CAN_IDE value. * @param[in] CAN_IDE the ID type of the message, this parameter can be one of the @ref CAN_Id_TypeDef enumeration. * @param[in] CAN_RTR the message type, this parameter can be one of the @ref CAN_RTR_TypeDef enumeration. * @param[in] CAN_DLC the number of data in the message type, this parameter can be a value between 0 to 7. * @param[in] CAN_Data pointer to a the @ref uint8_t table which contains data to sent. * @retval Transmit Status, this returned value can be one of the @ref CAN_TxStatus_TypeDef enumeration. */ CAN_TxStatus_TypeDef CAN_Transmit(uint32_t CAN_Id, CAN_Id_TypeDef CAN_IDE, CAN_RTR_TypeDef CAN_RTR, uint8_t CAN_DLC, uint8_t *CAN_Data) { CAN_TxStatus_TypeDef CAN_TxStatus = CAN_TxStatus_NoMailBox; CAN_Page_TypeDef can_page = CAN_GetSelectedPage(); /* Check the parameters */ assert_param(IS_CAN_IDTYPE_OK(CAN_IDE)); if (CAN_IDE != CAN_Id_Standard) { assert_param(IS_CAN_EXTID_OK(CAN_Id)); } else { assert_param(IS_CAN_STDID_OK(CAN_Id)); } assert_param(IS_CAN_RTR_OK(CAN_RTR)); assert_param(IS_CAN_DLC_OK(CAN_DLC)); /* Select one empty transmit mailbox */ if ((CAN->TPR & CAN_TPR_TME0) == CAN_TPR_TME0) { CAN_TxStatus = CAN_TxStatus_MailBox0Ok; } else if ((CAN->TPR & CAN_TPR_TME1) == CAN_TPR_TME1) { CAN_TxStatus = CAN_TxStatus_MailBox1Ok; } else if ((CAN->TPR & CAN_TPR_TME2) == CAN_TPR_TME2) { CAN_TxStatus = CAN_TxStatus_MailBox2Ok; } else { CAN_TxStatus = CAN_TxStatus_NoMailBox; } if (CAN_TxStatus != CAN_TxStatus_NoMailBox) { CAN->PSR = (uint8_t)CAN_TxStatus; /* Set up the Id */ if (CAN_IDE != CAN_Id_Standard) { CAN_Id &= (uint32_t)CAN_EXTID_SIZE; CAN->Page.TxMailbox.MIDR4 = (uint8_t)(CAN_Id); CAN_Id = CAN_Id>>8; CAN->Page.TxMailbox.MIDR3 = (uint8_t)(CAN_Id); CAN_Id = CAN_Id>>8; CAN->Page.TxMailbox.MIDR2 = (uint8_t)(CAN_Id); CAN_Id = CAN_Id>>8; CAN->Page.TxMailbox.MIDR1 = (uint8_t)(CAN_Id |CAN_IDE | CAN_RTR); } else { CAN_Id &= (uint16_t)CAN_STDID_SIZE; CAN->Page.TxMailbox.MIDR1 = (uint8_t)((CAN_Id>>6) | (CAN_RTR)) ; CAN->Page.TxMailbox.MIDR2 = (uint8_t)(CAN_Id<<2); } /* Set up the DLC */ /*clear old DLC value*/ CAN->Page.TxMailbox.MDLCR &= (uint8_t)0xF0; /*set the new value of DLC*/ CAN->Page.TxMailbox.MDLCR |= CAN_DLC; /* Set up the data field */ CAN->Page.TxMailbox.MDAR1 = CAN_Data[0]; CAN->Page.TxMailbox.MDAR2 = CAN_Data[1]; CAN->Page.TxMailbox.MDAR3 = CAN_Data[2]; CAN->Page.TxMailbox.MDAR4 = CAN_Data[3]; CAN->Page.TxMailbox.MDAR5 = CAN_Data[4]; CAN->Page.TxMailbox.MDAR6 = CAN_Data[5]; CAN->Page.TxMailbox.MDAR7 = CAN_Data[6]; CAN->Page.TxMailbox.MDAR8 = CAN_Data[7]; /* Request transmission */ CAN->Page.TxMailbox.MCSR |= CAN_MCSR_TXRQ; } /*Restore Last Page*/ CAN_SelectPage(can_page); return (CAN_TxStatus_TypeDef)CAN_TxStatus; } /** * @brief Checks the transmission of a message. * @param CAN_TransmitMailbox : the number of the mailbox that is used for transmission, can be on of @ref CAN_TransmitMailBox_TypeDef. * @retval CAN_TxStatus_Ok if the CAN driver transmits the message, CAN_TxStatus_Failed in an other case. */ CAN_TxStatus_TypeDef CAN_TransmitStatus(CAN_TransmitMailBox_TypeDef CAN_TransmitMailbox) { /* RQCP, TXOK and TME bits */ CAN_TxStatus_TypeDef tstate = CAN_TxStatus_Failed; uint8_t tmpstate=0; /* Check the parameters */ assert_param(IS_CAN_TRANSMITMAILBOX_OK(CAN_TransmitMailbox)); switch (CAN_TransmitMailbox) { case (CAN_TransmitMailBox_0): tmpstate = (uint8_t)((CAN->TSR & (uint8_t)(CAN_TSR_RQCP0|CAN_TSR_TXOK0))); tmpstate |= (uint8_t)((CAN->TPR & CAN_TPR_TME0)); break; case (CAN_TransmitMailBox_1): tmpstate = (uint8_t)((uint8_t)(CAN->TSR & (uint8_t)(CAN_TSR_RQCP1|CAN_TSR_TXOK1))>>1); tmpstate |= (uint8_t)((uint8_t)(CAN->TPR & CAN_TPR_TME1) >> 1); break; case (CAN_TransmitMailBox_2): tmpstate = (uint8_t)((uint8_t)(CAN->TSR & (uint8_t)(CAN_TSR_RQCP2|CAN_TSR_TXOK2))>>2); tmpstate |= (uint8_t)((uint8_t)(CAN->TPR & CAN_TPR_TME2) >> 2); break; default: tstate = CAN_TxStatus_Failed; break; } switch (tmpstate) { /*transmit pending */ case (0x00): tstate = CAN_TxStatus_Pending; break; /* transmit failed */ case (0x05): tstate = CAN_TxStatus_Failed; break; /* transmit succeeded */ case (0x15): tstate = CAN_TxStatus_Ok; break; /* transmit mailbox is empty : no activity on this TX mail box */ case (0x04): tstate = CAN_TxStatus_MailBoxEmpty; break; default: tstate = CAN_TxStatus_Failed; break; } return (CAN_TxStatus_TypeDef)tstate; } /** * @brief Cancels a transmit request. * @param CAN_TransmitMailbox : the Transmission mailbox, can be one of CAN_TransmitMailBox_TypeDef * @retval None */ void CAN_CancelTransmit(CAN_TransmitMailBox_TypeDef CAN_TransmitMailbox) { CAN_Page_TypeDef can_page = CAN_GetSelectedPage(); /* Check the parameters */ assert_param(IS_CAN_TRANSMITMAILBOX_OK(CAN_TransmitMailbox)); /*switch to the specific page */ CAN->PSR = (uint8_t)CAN_TransmitMailbox; /* abort transmission */ CAN->Page.TxMailbox.MCSR |= CAN_MCSR_ABRQ; /*Restore Last Page*/ CAN_SelectPage(can_page); } /** * @brief Releases the CAN FIFO. * @param None * @retval None */ void CAN_FIFORelease(void) { /* Release FIFO*/ CAN->RFR = CAN_RFR_RFOM; /*rc-w1*/ } /** * @brief Returns the number of pending messages. * @retval Number of pending messages. */ CAN_NbrPendingMessage_TypeDef CAN_MessagePending(void) { CAN_NbrPendingMessage_TypeDef msgpending = CAN_NbrPendingMessage_0; msgpending = (CAN_NbrPendingMessage_TypeDef)(CAN->RFR & CAN_RFR_FMP01); return (CAN_NbrPendingMessage_TypeDef)msgpending; } /** * @brief Receives a message which contains CAN Id, IDE, RTR * DLC, data and FMI number. * In order to get these data, use CAN_GetReceivedId(), CAN_GetReceivedIDE(), CAN_GetReceivedRTR(), * CAN_GetReceivedDLC(), CAN_GetReceivedFMI() and CAN_GetReceivedData() functions. * @param None * @retval None */ void CAN_Receive(void) { CAN_Page_TypeDef can_page = CAN_GetSelectedPage(); uint32_t temp1 = 0, temp2 = 0, temp3 = 0; /* select Fifo page*/ CAN->PSR = CAN_Page_RxFifo; /* Get the Id */ _IDE = (uint8_t)(CAN->Page.RxFIFO.MIDR1 & CAN_Id_Extended); if (_IDE != CAN_Id_Standard) { temp1 = ((uint32_t)((uint32_t)CAN->Page.RxFIFO.MIDR3) << 8); temp2 = ((uint32_t)((uint32_t)CAN->Page.RxFIFO.MIDR2) << 16); temp3 = ((uint32_t)((uint32_t)CAN->Page.RxFIFO.MIDR1 & 0x1F) << 24); _Id = (uint32_t)CAN_EXTID_SIZE & ((CAN->Page.RxFIFO.MIDR4) | temp1 | temp2 | temp3 ); } else { temp1 = (uint16_t)((uint16_t)((uint16_t)((uint16_t)CAN->Page.RxFIFO.MIDR1 & 0x1F) << 6)); temp2 = (uint16_t)((uint16_t)((uint16_t)CAN->Page.RxFIFO.MIDR2 >> 2)&0x3F); _Id = (uint16_t)CAN_STDID_SIZE & (temp1 | temp2 ); } _RTR = (uint8_t)((uint8_t)0x20 & CAN->Page.RxFIFO.MIDR1); /* Get the DLC */ _DLC = (uint8_t)(CAN->Page.RxFIFO.MDLCR & (uint8_t)0x0F); /* Get the FMI */ _FMI = CAN->Page.RxFIFO.MFMI; /* Get the data field */ _Data[0] = CAN->Page.RxFIFO.MDAR1; _Data[1] = CAN->Page.RxFIFO.MDAR2; _Data[2] = CAN->Page.RxFIFO.MDAR3; _Data[3] = CAN->Page.RxFIFO.MDAR4; _Data[4] = CAN->Page.RxFIFO.MDAR5; _Data[5] = CAN->Page.RxFIFO.MDAR6; _Data[6] = CAN->Page.RxFIFO.MDAR7; _Data[7] = CAN->Page.RxFIFO.MDAR8; /* Release the FIFO */ CAN_FIFORelease(); /*Restore Last Page*/ CAN_SelectPage(can_page); } /** * @brief Gets the CAN Id of the received message. * @param None * @retval the received CAN message Id. * @par Required preconditions: * This function is used to get data loaded by CAN_Receive function. * Before using this function, CAN_Receive function must be called. */ uint32_t CAN_GetReceivedId(void) { return (_Id); } /** * @brief Gets the CAN IDE of the received message. * @param None * @retval the received CAN message IDE. * @par Required preconditions: * This function is used to get data loaded by CAN_Receive function. * Before using this function, CAN_Receive function must be called. */ CAN_Id_TypeDef CAN_GetReceivedIDE(void) { return (CAN_Id_TypeDef)(_IDE); } /** * @brief Gets the CAN RTR of the received message. * @param None * @retval the received CAN message RTR. * @par Required preconditions: * This function is used to get data loaded by CAN_Receive function. * Before using this function, CAN_Receive function must be called. */ CAN_RTR_TypeDef CAN_GetReceivedRTR(void) { return (CAN_RTR_TypeDef)(_RTR); } /** * @brief Gets the CAN DLC of the received message. * @param None * @retval the received CAN message DLC. * @par Required preconditions: * This function is used to get data loaded by CAN_Receive function. * Before using this function, CAN_Receive function must be called. */ uint8_t CAN_GetReceivedDLC(void) { return (_DLC); } /** * @brief Gets the CAN Data of the received message. * @param CAN_DataIndex : number of the received Data, it can * be an integer between 0 to 7. * @retval the received CAN message ith Data. * @par Required preconditions: * This function is used to get data loaded by CAN_Receive function. * Before using this function, CAN_Receive function must be called. */ uint8_t CAN_GetReceivedData(uint8_t CAN_DataIndex) { assert_param(IS_CAN_DLC_OK(CAN_DataIndex)); return (_Data[CAN_DataIndex]); } /** * @brief Gets the CAN FMI of the received message. * @param None * @retval the received CAN message FMI. * @par Required preconditions: * This function is used to get data loaded by CAN_Receive function. * Before using this function, CAN_Receive function must be called. */ uint8_t CAN_GetReceivedFMI(void) { return (_FMI); } /** * @brief Returns the Received time stamp. * @param None * @retval uint16_t the received time stamp. */ uint16_t CAN_GetMessageTimeStamp(void) { uint16_t timestamp = 0; CAN_Page_TypeDef can_page = CAN_GetSelectedPage(); /*switch to the specific page */ CAN->PSR = CAN_Page_RxFifo; /* Get the Received Time stamp */ timestamp = CAN->Page.RxFIFO.MTSRL; timestamp |= (uint16_t)(((uint16_t)CAN->Page.RxFIFO.MTSRH)<<8); /*Restore Last Page*/ CAN_SelectPage(can_page); return (uint16_t)(timestamp); } /** * @brief Enters the Sleep low power mode. * @param None * @retval CAN_Sleep_Ok if sleep entered, CAN_Sleep_Failed in an other case. */ CAN_Sleep_TypeDef CAN_Sleep(void) { CAN_Sleep_TypeDef sleepstatus = CAN_Sleep_Failed; /* Request Sleep mode */ CAN->MCR = (uint8_t)((uint8_t)(CAN->MCR & (uint8_t)(~CAN_MCR_INRQ)) | CAN_MCR_SLEEP); /* Sleep mode status */ if ((CAN->MSR & (CAN_MSR_SLAK|CAN_MSR_INAK)) == CAN_MSR_SLAK) { /* Sleep mode not entered */ sleepstatus = CAN_Sleep_Ok; } /* At this step, sleep mode status */ return (CAN_Sleep_TypeDef) sleepstatus; } /** * @brief Wakes the CAN up. * @param None * @retval CAN_WakeUp_Ok if sleep mode left, CAN_WakeUp_Failed in an other case. */ CAN_WakeUp_TypeDef CAN_WakeUp(void) { CAN_WakeUp_TypeDef wakeupstatus = CAN_WakeUp_Failed; /* Wake up request */ CAN->MCR &= (uint8_t)(~CAN_MCR_SLEEP); /* Sleep mode status */ if ((CAN->MSR & CAN_MSR_SLAK) != CAN_MSR_SLAK) { /* Sleep mode exited */ wakeupstatus = CAN_WakeUp_Ok; } /* At this step, sleep mode status */ return (CAN_WakeUp_TypeDef)wakeupstatus; } /** * @brief Select the CAN Operation mode. * @param CAN_OperatingMode CAN Operating Mode , * this parameter can be one of @ref CAN_OperatingMode_TypeDef enumeration. * @retval the status of the requested mode which can be * - CAN_ModeStatus_Failed CAN failed entering the specific mode * - CAN_ModeStatus_Success CAN Succeed entering the specific mode */ CAN_ModeStatus_TypeDef CAN_OperatingModeRequest(CAN_OperatingMode_TypeDef CAN_OperatingMode) { uint16_t timeout = CAN_ACKNOWLEDGE_TIMEOUT; uint8_t modestatus = 0; assert_param(IS_CAN_OPERATINGMODE_OK(CAN_OperatingMode)); if (CAN_OperatingMode == CAN_OperatingMode_Initialization) { /* Request initialisation */ CAN->MCR = (uint8_t)((uint8_t)(CAN->MCR & (uint8_t)(~CAN_MCR_SLEEP)) | CAN_MCR_INRQ); /* Wait the acknowledge */ while (((CAN->MSR & CAN_MODE_MASK) != CAN_MSR_INAK) && (timeout != 0)) { timeout--; } if ((CAN->MSR & CAN_MODE_MASK) != CAN_MSR_INAK) { modestatus = CAN_ModeStatus_Failed; } else { modestatus = CAN_ModeStatus_Success; } } else if (CAN_OperatingMode == CAN_OperatingMode_Normal) { /* Request leave initialisation and sleep mode and enter Normal mode */ CAN->MCR &= (uint8_t)(~(CAN_MCR_SLEEP|CAN_MCR_INRQ)); /* Wait the acknowledge */ while (((CAN->MSR & CAN_MODE_MASK) != 0) && (timeout!=0)) { timeout--; } if ((CAN->MSR & CAN_MODE_MASK) != 0) { modestatus = CAN_ModeStatus_Failed; } else { modestatus = CAN_ModeStatus_Success; } } else if (CAN_OperatingMode == CAN_OperatingMode_Sleep) { /* Request Sleep mode */ CAN->MCR = (uint8_t)((uint8_t)(CAN->MCR & (uint8_t)(~CAN_MCR_INRQ)) | CAN_MCR_SLEEP); /* Wait the acknowledge */ while (((CAN->MSR & CAN_MODE_MASK) != CAN_MSR_SLAK) && (timeout!=0)) { timeout--; } if ((CAN->MSR & CAN_MODE_MASK) != CAN_MSR_SLAK) { modestatus = CAN_ModeStatus_Failed; } else { modestatus = CAN_ModeStatus_Success; } } else { modestatus = CAN_ModeStatus_Failed; } return (CAN_ModeStatus_TypeDef)(modestatus); } /** * @brief Gets the Last Error Code. * @param None * @retval Error Code. */ CAN_ErrorCode_TypeDef CAN_GetLastErrorCode(void) { CAN_ErrorCode_TypeDef errcode = CAN_ErrorCode_NoErr; CAN_Page_TypeDef can_page = CAN_GetSelectedPage(); CAN->PSR = CAN_Page_Config; errcode = (CAN_ErrorCode_TypeDef)((CAN->Page.Config.ESR) & (CAN_ESR_LEC)); /*Restore Last Page*/ CAN_SelectPage(can_page); return (CAN_ErrorCode_TypeDef)(errcode); } /** * @brief Clears the CAN's pending flags. * @param CAN_Flag : Flag to be cleared, can be one of the following parameters: * CAN_FLAG_RQCP0 Request MailBox0 Flag * CAN_FLAG_RQCP1 Request MailBox1 Flag * CAN_FLAG_RQCP2 Request MailBox2 Flag * CAN_FLAG_FF FIFO Full Flag * CAN_FLAG_FOV FIFO Overrun Flag * CAN_FLAG_WKU wake up Flag * CAN_FLAG_LEC Last error code Flag * @retval None */ void CAN_ClearFlag(CAN_FLAG_TypeDef CAN_Flag) { CAN_Page_TypeDef can_page = (CAN_Page_TypeDef)0; /* Check the parameters */ assert_param(IS_CAN_FLAG_CLEAR_OK(CAN_Flag)); if (((uint16_t)CAN_Flag & 0x0700)!= RESET) { if (((uint16_t)CAN_Flag & 0x020B)!= RESET) { /*Receive Flags*/ CAN->RFR = (uint8_t)(CAN_Flag); } else if (((uint16_t)CAN_Flag & 0x0403)!= RESET) { /*Transmit Flags*/ CAN->TSR = (uint8_t)(CAN_Flag); } else /*if((CAN_Flag & 0x0108)!=(uint16_t)RESET)*/ { /*wake up Flags*/ CAN->MSR = (uint8_t)(CAN_Flag); } } else { /*Error Flags*/ can_page = CAN_GetSelectedPage(); /* Clear the selected CAN flags */ CAN->PSR = CAN_Page_Config; CAN->Page.Config.ESR = (uint8_t)RESET; /*Restore Last Page*/ CAN_SelectPage(can_page); } } /** * @brief Checks whether the specified CAN flag is set or not. * @param CAN_Flag : specifies the flag to check, can be one of @ref CAN_FLAG_TypeDef enumeration. * @retval The new state of CAN_FLAG which can be one of @ref FlagStatus. */ FlagStatus CAN_GetFlagStatus(CAN_FLAG_TypeDef CAN_Flag) { FlagStatus bitstatus = RESET; CAN_Page_TypeDef can_page = (CAN_Page_TypeDef)0; /* Check the parameters */ assert_param(IS_CAN_FLAG_STATUS_OK(CAN_Flag)); if (((uint16_t)CAN_Flag & 0x0700)!= RESET) { if (((uint16_t)CAN_Flag & 0x020B)!= RESET) { /*Receive Flags*/ if ((CAN->RFR & (uint16_t)CAN_Flag )!= RESET) { /* CAN_FLAG is set */ bitstatus = SET; } else { /* CAN_FLAG is reset */ bitstatus = RESET; } } else if (((uint16_t)CAN_Flag & 0x0403)!= RESET) { /*Transmit Flags*/ if ((CAN->TSR & (uint16_t)CAN_Flag )!= RESET) { /* CAN_FLAG is set */ bitstatus = SET; } else { /* CAN_FLAG is reset */ bitstatus = RESET; } } else /*if((CAN_Flag & 0x0108)!=(uint16_t)RESET)*/ { /*wake up Flags*/ if ((CAN->MSR & (uint16_t)CAN_Flag )!= RESET) { /* CAN_FLAG is set */ bitstatus = SET; } else { /* CAN_FLAG is reset */ bitstatus = RESET; } } } else { /*Error Flags*/ can_page = CAN_GetSelectedPage(); CAN->PSR = CAN_Page_Config; if ((CAN->Page.Config.ESR & (uint16_t)CAN_Flag) != RESET) { /* CAN_FLAG is set */ bitstatus = SET; } else { /* CAN_FLAG is reset */ bitstatus = RESET; } /*Restore Last Page*/ CAN_SelectPage(can_page); } /* Return the CAN_FLAG status */ return (FlagStatus)bitstatus; } /** * @brief Checks whether the specified CAN interrupt has occurred or not. * @param CAN_IT: specifies the CAN interrupt source to check, can be one of @ref CAN_IT_TypeDef. * @retval The new state of CAN_IT, which can be one of @ref ITStatus. */ ITStatus CAN_GetITStatus(CAN_IT_TypeDef CAN_IT) { ITStatus pendingbitstatus = RESET; CAN_Page_TypeDef can_page = CAN_GetSelectedPage(); /* Check the parameters */ assert_param(IS_CAN_IT_STATUS_OK(CAN_IT)); switch (CAN_IT) { case CAN_IT_TME: if ((CAN->IER & CAN_IER_TMEIE) !=RESET) { pendingbitstatus = CheckITStatus(CAN->TSR, CAN_TSR_RQCP012); } else { pendingbitstatus = RESET; } break; case CAN_IT_FMP: if ((CAN->IER & CAN_IER_FMPIE) !=RESET) { pendingbitstatus = CheckITStatus(CAN->RFR, CAN_RFR_FMP01); } else { pendingbitstatus = RESET; } break; case CAN_IT_FF: if ((CAN->IER & CAN_IER_FFIE) !=RESET) { pendingbitstatus = CheckITStatus(CAN->RFR, CAN_RFR_FULL); } else { pendingbitstatus = RESET; } break; case CAN_IT_FOV: if ((CAN->IER & CAN_IER_FOVIE) !=RESET) { pendingbitstatus = CheckITStatus(CAN->RFR, CAN_RFR_FOVR); } else { pendingbitstatus = RESET; } break; case CAN_IT_WKU: if ((CAN->IER & CAN_IER_WKUIE) !=RESET) { pendingbitstatus = CheckITStatus(CAN->MSR, CAN_MSR_WKUI); } else { pendingbitstatus = RESET; } break; case CAN_IT_ERR: CAN->PSR = CAN_Page_Config; if ((CAN->Page.Config.EIER & CAN_EIER_ERRIE) !=RESET) { pendingbitstatus = CheckITStatus(CAN->Page.Config.ESR, CAN_ESR_EWGF|CAN_ESR_EPVF|CAN_ESR_BOFF|CAN_ESR_LEC); } else { pendingbitstatus = RESET; } break; case CAN_IT_EWG: CAN->PSR = CAN_Page_Config; if ((CAN->Page.Config.EIER & CAN_EIER_EWGIE) !=RESET) { pendingbitstatus = CheckITStatus(CAN->Page.Config.ESR, CAN_ESR_EWGF); } else { pendingbitstatus = RESET; } break; case CAN_IT_EPV: CAN->PSR = CAN_Page_Config; if ((CAN->Page.Config.EIER & CAN_EIER_EPVIE) !=RESET) { pendingbitstatus = CheckITStatus(CAN->Page.Config.ESR, CAN_ESR_EPVF); } else { pendingbitstatus = RESET; } break; case CAN_IT_BOF: CAN->PSR = CAN_Page_Config; if ((CAN->Page.Config.EIER & CAN_EIER_BOFIE) !=RESET) { pendingbitstatus = CheckITStatus(CAN->Page.Config.ESR, CAN_ESR_BOFF); } else { pendingbitstatus = RESET; } break; case CAN_IT_LEC: CAN->PSR = CAN_Page_Config; if ((CAN->Page.Config.EIER & CAN_EIER_LECIE) !=RESET) { pendingbitstatus = CheckITStatus(CAN->Page.Config.ESR, CAN_ESR_LEC); } else { pendingbitstatus = RESET; } break; default : pendingbitstatus = RESET; break; } /*Restore Last Page*/ CAN_SelectPage(can_page); /* Return the CAN_IT status */ return (ITStatus)pendingbitstatus; } /** * @brief Clears the CAN’s interrupt pending bits. * @param CAN_IT: specifies the interrupt pending bit to clear, * can be one of the following parameters: * CAN_IT_TME = Transmit mailbox empty interrupt * CAN_IT_FF =FIFO full interrupt * CAN_IT_FOV =FIFO overrun interrupt * CAN_IT_WKU =Wake-up interrupt * CAN_IT_ERR =General Error interrupt * CAN_IT_EWG =Error warning interrupt * CAN_IT_EPV =Error passive interrupt * CAN_IT_BOF = Bus-off interrupt * CAN_IT_LEC =Last error code interrupt * @retval None */ void CAN_ClearITPendingBit(CAN_IT_TypeDef CAN_IT) { CAN_Page_TypeDef can_page = CAN_GetSelectedPage(); /* Check the parameters */ assert_param(IS_CAN_IT_PENDING_BIT_OK(CAN_IT)); switch (CAN_IT) { case CAN_IT_TME: CAN->TSR = CAN_TSR_RQCP012;/* rc_w1*/ break; case CAN_IT_FF: CAN->RFR = CAN_RFR_FULL; /* rc_w1*/ break; case CAN_IT_FOV: CAN->RFR = CAN_RFR_FOVR; /* rc_w1*/ break; case CAN_IT_WKU: CAN->MSR = CAN_MSR_WKUI; /* rc_w1*/ break; case CAN_IT_ERR: CAN->PSR = CAN_Page_Config; CAN->Page.Config.ESR = (uint8_t)CAN_ESR_RESET_VALUE; CAN->MSR = CAN_MSR_ERRI; break; case CAN_IT_EWG: CAN->MSR = CAN_MSR_ERRI; break; case CAN_IT_EPV: CAN->MSR = CAN_MSR_ERRI; break; case CAN_IT_BOF: CAN->MSR = CAN_MSR_ERRI; break; case CAN_IT_LEC: CAN->PSR = CAN_Page_Config; CAN->Page.Config.ESR = (uint8_t)CAN_ESR_RESET_VALUE; break; default : break; } /*Restore Last Page*/ CAN_SelectPage(can_page); } /** * @brief Gets the selected registers page. * @param None * @retval the selected page which can be one of the @ref CAN_Page_TypeDef. */ CAN_Page_TypeDef CAN_GetSelectedPage(void) { return (CAN_Page_TypeDef)(CAN->PSR); } /** * @brief Sets the registers page to be selected. * @param CAN_Page: the selected page which can be one of the @ref CAN_Page_TypeDef. * @retval None */ void CAN_SelectPage(CAN_Page_TypeDef CAN_Page) { CAN->PSR = (uint8_t)CAN_Page; } /** * @brief Checks whether the CAN interrupt has occurred or not. * @param CAN_Reg: specifies the CAN interrupt register to check. * @param It_Bit: specifies the interrupt source bit to check. * @retval The new state of the CAN Interrupt, which can be one of ITStatus. */ static ITStatus CheckITStatus(uint8_t CAN_Reg, uint8_t It_Bit) { ITStatus pendingbitstatus = RESET; if ((CAN_Reg & It_Bit) != (uint8_t)RESET) { /* CAN_IT is set */ pendingbitstatus = SET; } else { /* CAN_IT is reset */ pendingbitstatus = RESET; } return (ITStatus)pendingbitstatus; } /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
SeanGau/Arduino_Core_STM8
cores/arduino/stm8/STM8_StdPeriph_Driver/stm8xx_rtc.c
<filename>cores/arduino/stm8/STM8_StdPeriph_Driver/stm8xx_rtc.c #if defined (STM8Lxx) #include "stm8l15x_rtc.c" #endif
SeanGau/Arduino_Core_STM8
cores/arduino/stm8/timer.h
<reponame>SeanGau/Arduino_Core_STM8<gh_stars>100-1000 /** ****************************************************************************** * @file timer.h * @author WI6LABS * @version V1.0.0 * @date 16-September-2016 * @brief Header for timer module ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __TIMER_H #define __TIMER_H /* Includes ------------------------------------------------------------------*/ #include "stm8_def.h" #include "PeripheralPins.h" #ifdef __cplusplus extern "C" { #endif /* Exported types ------------------------------------------------------------*/ typedef enum { TIM1_E = 0, TIM2_E, TIM3_E, TIM4_E, NB_TIMER_MANAGED } timer_id_e; typedef enum { bits_8 = 0xFF, bits_16 = 0xFFFF } timer_prescaler_limit; typedef enum { TIMER_PWM = 0x00000000, TIMER_RESERVED = 0x00000001, TIMER_OTHER = 0x00000002 } timer_mode_e; typedef struct { uint8_t pin; int32_t count; uint8_t state; } timer_toggle_pin_config_str; /// @brief defines the global attributes of the TIMER typedef struct { timer_id_e timer_id; void (*irqHandle)(timer_id_e); void (*irqHandleOC)(timer_id_e, uint8_t); timer_mode_e timer_mode; timer_prescaler_limit prescalerLimit; timer_toggle_pin_config_str toggle_pin; uint8_t configured; } timer_conf_t; /* Exported constants --------------------------------------------------------*/ #define MAX_FREQ 65535 /* Exported macro ------------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ void TimerHandleInit(timer_id_e timer_id, uint16_t period, uint16_t prescaler); void TimerHandleDeinit(timer_id_e timer_id); void attachIntHandle(timer_id_e timer_id, void (*irqHandle)(timer_id_e)); void TIM_PeriodElapsedCallback(timer_id_e timer_id); void TimerPinInit(uint8_t _pin, uint32_t frequency, uint32_t duration); void TimerPinDeinit(uint8_t _pin); void TimerPulseInit(timer_id_e timer_id, uint16_t period, uint16_t pulseWidth, void (*irqHandle)(timer_id_e, uint8_t)); void TimerPulseDeinit(timer_id_e timer_id); void TIM_OC_DelayElapsedCallback(timer_id_e timer_id); uint16_t getTimerCounter(timer_id_e timer_id); void setTimerCounter(timer_id_e timer_id, uint16_t value); void setCCRRegister(timer_id_e timer_id, uint8_t channel, uint16_t value); #ifdef __cplusplus } #endif #endif /* __TIMER_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
SeanGau/Arduino_Core_STM8
cores/arduino/stm8/STM8_StdPeriph_Driver/stm8xx_awu.c
<reponame>SeanGau/Arduino_Core_STM8 #if defined (STM8Sxx) #include "stm8s_awu.c" #endif
SeanGau/Arduino_Core_STM8
cores/arduino/stm8/STM8_StdPeriph_Driver/stm8xx_spi.c
<reponame>SeanGau/Arduino_Core_STM8 #if defined (STM8Sxx) #include "stm8s_spi.c" #elif defined (STM8Lxx) #include "stm8l15x_spi.c" #endif
SeanGau/Arduino_Core_STM8
cores/arduino/stm8/STM8_StdPeriph_Driver/stm8xx_uart3.c
#if !defined(NO_HWSERIAL) #if defined(STM8S208) ||defined(STM8S207) || defined(STM8S007) || defined (STM8AF52Ax) ||\ defined (STM8AF62Ax) #include "stm8s_uart3.c" #endif #endif /* !NO_HWSERIAL */
SeanGau/Arduino_Core_STM8
cores/arduino/stm8/PinAF_STM8Lxx.h
<filename>cores/arduino/stm8/PinAF_STM8Lxx.h /* ******************************************************************************* * Copyright (c) 2018, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************* */ #ifndef _PINAF_STM8LXX_H #define _PINAF_STM8LXX_H #ifdef STM8Lxx #ifdef __cplusplus extern "C" { #endif enum { AFIO_NONE, AFIO_SPI1_FULL_ENABLE, AFIO_SPI1_FULL_DISABLE, AFIO_SPI1_PORTF_ENABLE, AFIO_SPI1_PORTF_DISABLE, AFIO_SPI2_ENABLE, AFIO_SPI2_DISABLE, AFIO_USART1_PORTA_ENABLE, AFIO_USART1_PORTA_DISABLE, AFIO_USART1_PORTC_ENABLE, AFIO_USART1_PORTC_DISABLE, AFIO_USART1_CLK_ENABLE, AFIO_USART1_CLK_DISABLE, AFIO_USART3_PORTF_ENABLE, AFIO_USART3_PORTF_DISABLE, AFIO_USART3_Clk_ENABLE, AFIO_USART3_Clk_DISABLE, AFIO_TIM2_CH1_ENABLE, AFIO_TIM2_CH1_DISABLE, AFIO_TIM2_CH2_ENABLE, AFIO_TIM2_CH2_DISABLE, AFIO_TIM2_TRIGPortA_ENABLE, AFIO_TIM2_TRIGPortA_DISABLE, AFIO_TIM2_TRIGLSE_ENABLE, AFIO_TIM2_TRIGLSE_DISABLE, AFIO_TIM2_TIM3_BKIN_ENABLE, AFIO_TIM2_TIM3_BKIN_DISABLE, AFIO_TIM3_CH1_ENABLE, AFIO_TIM3_CH1_DISABLE, AFIO_TIM3_CH2_ENABLE, AFIO_TIM3_CH2_DISABLE, AFIO_TIM3_TRIGPortA_ENABLE, AFIO_TIM3_TRIGPortA_DISABLE, AFIO_TIM3_TRIGPortG_ENABLE, AFIO_TIM3_TRIGPortG_DISABLE, AFIO_TIM3_TRIGLSE_ENABLE, AFIO_TIM3_TRIGLSE_DISABLE, AFIO_ADC1_EXTRIG_ENABLE, AFIO_ADC1_EXTRIG_DISABLE, AFIO_CCO_ENABLE, AFIO_CCO_DISABLE }; static inline void pin_Set8LAFPin(uint16_t afnum) { switch (afnum) { case AFIO_SPI1_FULL_ENABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_SPI1Full, ENABLE); break; case AFIO_SPI1_FULL_DISABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_SPI1Full, DISABLE); break; case AFIO_SPI1_PORTF_ENABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_SPI1PortF, ENABLE); break; case AFIO_SPI1_PORTF_DISABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_SPI1PortF, DISABLE); break; case AFIO_SPI2_ENABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_SPI2Full, ENABLE); break; case AFIO_SPI2_DISABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_SPI2Full, DISABLE); break; case AFIO_USART1_PORTA_ENABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_USART1TxRxPortA, ENABLE); break; case AFIO_USART1_PORTA_DISABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_USART1TxRxPortA, DISABLE); break; case AFIO_USART1_PORTC_ENABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_USART1TxRxPortC, ENABLE); break; case AFIO_USART1_PORTC_DISABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_USART1TxRxPortC, DISABLE); break; case AFIO_USART1_CLK_ENABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_USART1Clk, ENABLE); break; case AFIO_USART1_CLK_DISABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_USART1Clk, DISABLE); break; case AFIO_USART3_PORTF_ENABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_USART3TxRxPortF, ENABLE); break; case AFIO_USART3_PORTF_DISABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_USART3TxRxPortF, DISABLE); break; case AFIO_USART3_Clk_ENABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_USART3Clk, ENABLE); break; case AFIO_USART3_Clk_DISABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_USART3Clk, DISABLE); break; case AFIO_TIM2_CH1_ENABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_TIM2Channel1, ENABLE); break; case AFIO_TIM2_CH1_DISABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_TIM2Channel1, DISABLE); break; case AFIO_TIM2_CH2_ENABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_TIM2Channel2, ENABLE); break; case AFIO_TIM2_CH2_DISABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_TIM2Channel2, DISABLE); break; case AFIO_TIM2_TRIGPortA_ENABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_TIM2TRIGPortA, ENABLE); break; case AFIO_TIM2_TRIGPortA_DISABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_TIM2TRIGPortA, DISABLE); break; case AFIO_TIM2_TRIGLSE_ENABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_TIM2TRIGLSE, ENABLE); break; case AFIO_TIM2_TRIGLSE_DISABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_TIM2TRIGLSE, DISABLE); break; case AFIO_TIM2_TIM3_BKIN_ENABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_TIM23BKIN, ENABLE); break; case AFIO_TIM2_TIM3_BKIN_DISABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_TIM23BKIN, DISABLE); break; case AFIO_TIM3_CH1_ENABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_TIM3Channel1, ENABLE); break; case AFIO_TIM3_CH1_DISABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_TIM3Channel1, DISABLE); break; case AFIO_TIM3_CH2_ENABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_TIM3Channel2, ENABLE); break; case AFIO_TIM3_CH2_DISABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_TIM3Channel2, DISABLE); break; case AFIO_TIM3_TRIGPortA_ENABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_TIM3TRIGPortA, ENABLE); break; case AFIO_TIM3_TRIGPortA_DISABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_TIM3TRIGPortA, DISABLE); break; case AFIO_TIM3_TRIGPortG_ENABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_TIM3TRIGPortG, ENABLE); break; case AFIO_TIM3_TRIGPortG_DISABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_TIM3TRIGPortG, DISABLE); break; case AFIO_TIM3_TRIGLSE_ENABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_TIM3TRIGLSE, ENABLE); break; case AFIO_TIM3_TRIGLSE_DISABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_TIM3TRIGLSE, DISABLE); break; case AFIO_ADC1_EXTRIG_ENABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_ADC1ExtTRIG1, ENABLE); break; case AFIO_ADC1_EXTRIG_DISABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_ADC1ExtTRIG1, DISABLE); break; case AFIO_CCO_ENABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_CCO, ENABLE); break; case AFIO_CCO_DISABLE: SYSCFG_REMAPPinConfig(REMAP_Pin_CCO, DISABLE); break; default: case AFIO_NONE: break; } } #ifdef __cplusplus } // extern "C" #endif // __cplusplus #endif //STM8Lxx #endif //_PINAF_STM8LXX_H
SeanGau/Arduino_Core_STM8
cores/arduino/stm8/STM8_StdPeriph_Driver/stm8xx_dma.c
<reponame>SeanGau/Arduino_Core_STM8 #if defined (STM8Lxx) #include "stm8l15x_dma.c" #endif
SeanGau/Arduino_Core_STM8
cores/arduino/stm8/twi.h
/** ****************************************************************************** * @file twi.h * @author WI6LABS * @version V1.0.0 * @date * @brief Header for twi module ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef __TWI_H__ #define __TWI_H__ /* Includes ------------------------------------------------------------------*/ #include "stm8_def.h" #include "PeripheralPins.h" #ifdef __cplusplus extern "C" { #endif /* Exported macro ------------------------------------------------------------*/ #if defined(STM8Lxx) #define I2C_AddMode_TypeDef I2C_AcknowledgedAddress_TypeDef #define I2C_ADDMODE_7BIT I2C_AcknowledgedAddress_7bit #endif /* Exported types ------------------------------------------------------------*/ /* I2C Tx/Rx buffer size */ #define I2C_TX_RX_BUFFER_SIZE 32 typedef struct i2c_s i2c_t; struct i2c_s { /* The 1st 2 members I2CName i2c * and I2C_HandleTypeDef handle should * be kept as the first members of this struct * to have get_i2c_obj() function work as expected */ #if defined(STM8Lxx) I2C_TypeDef* I2Cx; #endif uint8_t init_done; PinName sda; PinName scl; I2C_AddMode_TypeDef addressingMode; uint16_t Address; uint8_t isMaster; void (*i2c_onSlaveReceive)(uint8_t *, int); void (*i2c_onSlaveTransmit)(void); uint8_t i2cTxRxBuffer[I2C_TX_RX_BUFFER_SIZE]; uint8_t i2cTxRxBufferSize; uint8_t txCounter; }; ///@brief I2C state typedef enum { I2C_OK = 0, I2C_TIMEOUT = 1, I2C_ERROR = 2, I2C_BUSY = 3 } i2c_status_e; #define I2C_DEFAULT_SPEED ((uint32_t)100000) #define I2C_DELAY_MAX ((uint16_t)1000) /* Exported constants --------------------------------------------------------*/ /* Exported functions ------------------------------------------------------- */ void i2c_init(i2c_t *obj); void i2c_custom_init(i2c_t *obj, uint32_t timing, I2C_AddMode_TypeDef addressingMode, uint16_t ownAddress, uint8_t master); void i2c_deinit(i2c_t *obj); void i2c_setTiming(i2c_t *obj, uint32_t frequency); i2c_status_e i2c_master_write(i2c_t *obj, uint8_t dev_address, uint8_t *data, uint8_t size); i2c_status_e i2c_master_read(i2c_t *obj, uint8_t dev_address, uint8_t *data, uint8_t size); void i2c_slave_write_IT(i2c_t *obj, uint8_t *data, uint8_t size); void i2c_attachSlaveRxEvent(i2c_t *obj, void (*function)(uint8_t *, int)); void i2c_attachSlaveTxEvent(i2c_t *obj, void (*function)(void)); void I2C_slaveITCallback(i2c_t *obj); uint32_t getRegistre(void); #ifdef __cplusplus } #endif #endif /* __TWI_H__ */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
SeanGau/Arduino_Core_STM8
system/Drivers/STM8Sxx_StdPeriph_Driver/src/stm8s_tim4.c
/** ****************************************************************************** * @file stm8s_tim4.c * @author MCD Application Team * @version V2.3.0 * @date 16-June-2017 * @brief This file contains all the functions for the TIM4 peripheral. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT 2014 STMicroelectronics</center></h2> * * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License"); * You may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.st.com/software_license_agreement_liberty_v2 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm8s_tim4.h" /** @addtogroup STM8S_StdPeriph_Driver * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /** * @addtogroup TIM4_Public_Functions * @{ */ /** * @brief Deinitializes the TIM4 peripheral registers to their default reset values. * @param None * @retval None */ void TIM4_DeInit(void) { TIM4->CR1 = TIM4_CR1_RESET_VALUE; TIM4->IER = TIM4_IER_RESET_VALUE; TIM4->CNTR = TIM4_CNTR_RESET_VALUE; TIM4->PSCR = TIM4_PSCR_RESET_VALUE; TIM4->ARR = TIM4_ARR_RESET_VALUE; TIM4->SR1 = TIM4_SR1_RESET_VALUE; } /** * @brief Initializes the TIM4 Time Base Unit according to the specified parameters. * @param TIM4_Prescaler specifies the Prescaler from TIM4_Prescaler_TypeDef. * @param TIM4_Period specifies the Period value. * @retval None */ void TIM4_TimeBaseInit(TIM4_Prescaler_TypeDef TIM4_Prescaler, uint8_t TIM4_Period) { /* Check TIM4 prescaler value */ assert_param(IS_TIM4_PRESCALER_OK(TIM4_Prescaler)); /* Set the Prescaler value */ TIM4->PSCR = (uint8_t)(TIM4_Prescaler); /* Set the Autoreload value */ TIM4->ARR = (uint8_t)(TIM4_Period); } /** * @brief Enables or disables the TIM4 peripheral. * @param NewState new state of the TIM4 peripheral. This parameter can * be ENABLE or DISABLE. * @retval None */ void TIM4_Cmd(FunctionalState NewState) { /* Check the parameters */ assert_param(IS_FUNCTIONALSTATE_OK(NewState)); /* set or Reset the CEN Bit */ if (NewState != DISABLE) { TIM4->CR1 |= TIM4_CR1_CEN; } else { TIM4->CR1 &= (uint8_t)(~TIM4_CR1_CEN); } } /** * @brief Enables or disables the specified TIM4 interrupts. * @param NewState new state of the TIM4 peripheral. * This parameter can be: ENABLE or DISABLE. * @param TIM4_IT specifies the TIM4 interrupts sources to be enabled or disabled. * This parameter can be any combination of the following values: * - TIM4_IT_UPDATE: TIM4 update Interrupt source * @param NewState new state of the TIM4 peripheral. * @retval None */ void TIM4_ITConfig(TIM4_IT_TypeDef TIM4_IT, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_TIM4_IT_OK(TIM4_IT)); assert_param(IS_FUNCTIONALSTATE_OK(NewState)); if (NewState != DISABLE) { /* Enable the Interrupt sources */ TIM4->IER |= (uint8_t)TIM4_IT; } else { /* Disable the Interrupt sources */ TIM4->IER &= (uint8_t)(~TIM4_IT); } } /** * @brief Enables or Disables the TIM4 Update event. * @param NewState new state of the TIM4 peripheral Preload register. This parameter can * be ENABLE or DISABLE. * @retval None */ void TIM4_UpdateDisableConfig(FunctionalState NewState) { /* Check the parameters */ assert_param(IS_FUNCTIONALSTATE_OK(NewState)); /* Set or Reset the UDIS Bit */ if (NewState != DISABLE) { TIM4->CR1 |= TIM4_CR1_UDIS; } else { TIM4->CR1 &= (uint8_t)(~TIM4_CR1_UDIS); } } /** * @brief Selects the TIM4 Update Request Interrupt source. * @param TIM4_UpdateSource specifies the Update source. * This parameter can be one of the following values * - TIM4_UPDATESOURCE_REGULAR * - TIM4_UPDATESOURCE_GLOBAL * @retval None */ void TIM4_UpdateRequestConfig(TIM4_UpdateSource_TypeDef TIM4_UpdateSource) { /* Check the parameters */ assert_param(IS_TIM4_UPDATE_SOURCE_OK(TIM4_UpdateSource)); /* Set or Reset the URS Bit */ if (TIM4_UpdateSource != TIM4_UPDATESOURCE_GLOBAL) { TIM4->CR1 |= TIM4_CR1_URS; } else { TIM4->CR1 &= (uint8_t)(~TIM4_CR1_URS); } } /** * @brief Selects the TIM4’s One Pulse Mode. * @param TIM4_OPMode specifies the OPM Mode to be used. * This parameter can be one of the following values * - TIM4_OPMODE_SINGLE * - TIM4_OPMODE_REPETITIVE * @retval None */ void TIM4_SelectOnePulseMode(TIM4_OPMode_TypeDef TIM4_OPMode) { /* Check the parameters */ assert_param(IS_TIM4_OPM_MODE_OK(TIM4_OPMode)); /* Set or Reset the OPM Bit */ if (TIM4_OPMode != TIM4_OPMODE_REPETITIVE) { TIM4->CR1 |= TIM4_CR1_OPM; } else { TIM4->CR1 &= (uint8_t)(~TIM4_CR1_OPM); } } /** * @brief Configures the TIM4 Prescaler. * @param Prescaler specifies the Prescaler Register value * This parameter can be one of the following values * - TIM4_PRESCALER_1 * - TIM4_PRESCALER_2 * - TIM4_PRESCALER_4 * - TIM4_PRESCALER_8 * - TIM4_PRESCALER_16 * - TIM4_PRESCALER_32 * - TIM4_PRESCALER_64 * - TIM4_PRESCALER_128 * @param TIM4_PSCReloadMode specifies the TIM4 Prescaler Reload mode. * This parameter can be one of the following values * - TIM4_PSCRELOADMODE_IMMEDIATE: The Prescaler is loaded * immediately. * - TIM4_PSCRELOADMODE_UPDATE: The Prescaler is loaded at * the update event. * @retval None */ void TIM4_PrescalerConfig(TIM4_Prescaler_TypeDef Prescaler, TIM4_PSCReloadMode_TypeDef TIM4_PSCReloadMode) { /* Check the parameters */ assert_param(IS_TIM4_PRESCALER_RELOAD_OK(TIM4_PSCReloadMode)); assert_param(IS_TIM4_PRESCALER_OK(Prescaler)); /* Set the Prescaler value */ TIM4->PSCR = (uint8_t)Prescaler; /* Set or reset the UG Bit */ TIM4->EGR = (uint8_t)TIM4_PSCReloadMode; } /** * @brief Enables or disables TIM4 peripheral Preload register on ARR. * @param NewState new state of the TIM4 peripheral Preload register. * This parameter can be ENABLE or DISABLE. * @retval None */ void TIM4_ARRPreloadConfig(FunctionalState NewState) { /* Check the parameters */ assert_param(IS_FUNCTIONALSTATE_OK(NewState)); /* Set or Reset the ARPE Bit */ if (NewState != DISABLE) { TIM4->CR1 |= TIM4_CR1_ARPE; } else { TIM4->CR1 &= (uint8_t)(~TIM4_CR1_ARPE); } } /** * @brief Configures the TIM4 event to be generated by software. * @param TIM4_EventSource specifies the event source. * This parameter can be one of the following values: * - TIM4_EVENTSOURCE_UPDATE: TIM4 update Event source * @retval None */ void TIM4_GenerateEvent(TIM4_EventSource_TypeDef TIM4_EventSource) { /* Check the parameters */ assert_param(IS_TIM4_EVENT_SOURCE_OK(TIM4_EventSource)); /* Set the event sources */ TIM4->EGR = (uint8_t)(TIM4_EventSource); } /** * @brief Sets the TIM4 Counter Register value. * @param Counter specifies the Counter register new value. * This parameter is between 0x00 and 0xFF. * @retval None */ void TIM4_SetCounter(uint8_t Counter) { /* Set the Counter Register value */ TIM4->CNTR = (uint8_t)(Counter); } /** * @brief Sets the TIM4 Autoreload Register value. * @param Autoreload specifies the Autoreload register new value. * This parameter is between 0x00 and 0xFF. * @retval None */ void TIM4_SetAutoreload(uint8_t Autoreload) { /* Set the Autoreload Register value */ TIM4->ARR = (uint8_t)(Autoreload); } /** * @brief Gets the TIM4 Counter value. * @param None * @retval Counter Register value. */ uint8_t TIM4_GetCounter(void) { /* Get the Counter Register value */ return (uint8_t)(TIM4->CNTR); } /** * @brief Gets the TIM4 Prescaler value. * @param None * @retval Prescaler Register configuration value. */ TIM4_Prescaler_TypeDef TIM4_GetPrescaler(void) { /* Get the Prescaler Register value */ return (TIM4_Prescaler_TypeDef)(TIM4->PSCR); } /** * @brief Checks whether the specified TIM4 flag is set or not. * @param TIM4_FLAG specifies the flag to check. * This parameter can be one of the following values: * - TIM4_FLAG_UPDATE: TIM4 update Flag * @retval FlagStatus The new state of TIM4_FLAG (SET or RESET). */ FlagStatus TIM4_GetFlagStatus(TIM4_FLAG_TypeDef TIM4_FLAG) { FlagStatus bitstatus = RESET; /* Check the parameters */ assert_param(IS_TIM4_GET_FLAG_OK(TIM4_FLAG)); if ((TIM4->SR1 & (uint8_t)TIM4_FLAG) != 0) { bitstatus = SET; } else { bitstatus = RESET; } return ((FlagStatus)bitstatus); } /** * @brief Clears the TIM4’s pending flags. * @param TIM4_FLAG specifies the flag to clear. * This parameter can be one of the following values: * - TIM4_FLAG_UPDATE: TIM4 update Flag * @retval None. */ void TIM4_ClearFlag(TIM4_FLAG_TypeDef TIM4_FLAG) { /* Check the parameters */ assert_param(IS_TIM4_GET_FLAG_OK(TIM4_FLAG)); /* Clear the flags (rc_w0) clear this bit by writing 0. Writing ‘1’ has no effect*/ TIM4->SR1 = (uint8_t)(~TIM4_FLAG); } /** * @brief Checks whether the TIM4 interrupt has occurred or not. * @param TIM4_IT specifies the TIM4 interrupt source to check. * This parameter can be one of the following values: * - TIM4_IT_UPDATE: TIM4 update Interrupt source * @retval ITStatus The new state of the TIM4_IT (SET or RESET). */ ITStatus TIM4_GetITStatus(TIM4_IT_TypeDef TIM4_IT) { ITStatus bitstatus = RESET; uint8_t itstatus = 0x0, itenable = 0x0; /* Check the parameters */ assert_param(IS_TIM4_IT_OK(TIM4_IT)); itstatus = (uint8_t)(TIM4->SR1 & (uint8_t)TIM4_IT); itenable = (uint8_t)(TIM4->IER & (uint8_t)TIM4_IT); if ((itstatus != (uint8_t)RESET ) && (itenable != (uint8_t)RESET )) { bitstatus = (ITStatus)SET; } else { bitstatus = (ITStatus)RESET; } return ((ITStatus)bitstatus); } /** * @brief Clears the TIM4's interrupt pending bits. * @param TIM4_IT specifies the pending bit to clear. * This parameter can be one of the following values: * - TIM4_IT_UPDATE: TIM4 update Interrupt source * @retval None. */ void TIM4_ClearITPendingBit(TIM4_IT_TypeDef TIM4_IT) { /* Check the parameters */ assert_param(IS_TIM4_IT_OK(TIM4_IT)); /* Clear the IT pending Bit */ TIM4->SR1 = (uint8_t)(~TIM4_IT); } /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
SeanGau/Arduino_Core_STM8
cores/arduino/stm8/STM8_StdPeriph_Driver/stm8xx_itc.c
<reponame>SeanGau/Arduino_Core_STM8 #if defined (STM8Sxx) #include "stm8s_itc.c" #elif defined (STM8Lxx) #include "stm8l15x_itc.c" #endif
SeanGau/Arduino_Core_STM8
variants/NUCLEO_8L152R8/stm8l15x_it.c
<reponame>SeanGau/Arduino_Core_STM8 /** ****************************************************************************** * @file Project/STM8L15x_StdPeriph_Template/stm8l15x_it.c * @author MCD Application Team * @version V1.6.1 * @date 30-September-2014 * @brief Main Interrupt Service Routines. * This file provides template for all peripherals interrupt service routine. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT 2014 STMicroelectronics</center></h2> * * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License"); * You may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.st.com/software_license_agreement_liberty_v2 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm8_it.h" #ifdef __cplusplus extern "C" { #endif /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /* Public functions ----------------------------------------------------------*/ #ifdef _COSMIC_ extern void _stext(); /* startup routine */ #pragma section const {vector} void (* const @vector _vectab[32])() = { _stext, /* RESET */ TRAP_IRQHandler, /* TRAP */ NonHandledInterrupt, /* Reserved */ FLASH_IRQHandler, /*FLASH interrupt */ DMA1_CHANNEL0_1_IRQHandler, /*DMA1 channel0 and channel1 interrupt */ DMA1_CHANNEL2_3_IRQHandler, /*DMA1 channel2 and channel3 interrupt */ RTC_CSSLSE_IRQHandler, /* irq4 - RTC/ CSS on LSE interrupt */ EXTIE_F_PVD_IRQHandler, /* irq5 - External IT PORTE/F interrupt /PVD interrupt*/ EXTIB_G_IRQHandler, /* irq6 - External IT PORTB / PORTG interrupt */ EXTID_H_IRQHandler, /* irq7 - External IT PORTD / PORTH interrupt */ EXTI0_IRQHandler, /* irq8 - External IT PIN0 interrupt */ EXTI1_IRQHandler, /* irq9 - External IT PIN1 interrupt */ EXTI2_IRQHandler, /* irq10 - External IT PIN2 interrupt */ EXTI3_IRQHandler, /* irq11 - External IT PIN3 interrupt */ EXTI4_IRQHandler, /* irq12 - External IT PIN4 interrupt */ EXTI5_IRQHandler, /* irq13 - External IT PIN5 interrupt */ EXTI6_IRQHandler, /* irq14 - External IT PIN6 interrupt */ EXTI7_IRQHandler, /* irq15 - External IT PIN7 interrupt */ LCD_AES_IRQHandler, /* irq16 - LCD / AES interrupt */ SWITCH_CSS_BREAK_DAC_IRQHandler, /* irq17 - CLK switch/CSS interrupt/ TIM1 Break interrupt / DAC */ ADC1_COMP_IRQHandler, /* irq18 - ADC1 and Comparator interrupt */ TIM2_UPD_OVF_TRG_BRK_USART2_TX_IRQHandler, /* irq19 - TIM2 Update/Overflow/Trigger/Break / USART2 TX interrupt */ TIM2_CC_USART2_RX_IRQHandler, /* irq20 - TIM2 Capture/Compare / USART2 RX interrupt */ TIM3_UPD_OVF_TRG_BRK_USART3_TX_IRQHandler, /* irq21 - TIM3 Update/Overflow/Trigger/Break / USART3 TX interrupt */ TIM3_CC_USART3_RX_IRQHandler, /* irq22 - TIM3 Capture/Compare /USART3 RX interrupt */ TIM1_UPD_OVF_TRG_COM_IRQHandler, /* irq23 - TIM1 Update/Overflow/Trigger/Commutation interrupt */ TIM1_CC_IRQHandler, /* irq24 - TIM1 Capture/Compare interrupt */ TIM4_UPD_OVF_TRG_IRQHandler, /* irq25 - TIM4 Update/Overflow/Trigger interrupt */ SPI1_IRQHandler, /* irq26 - SPI1 interrupt */ USART1_TX_TIM5_UPD_OVF_TRG_BRK_IRQHandler, /* irq27 - USART1 TX / TIM5 Update/Overflow/Trigger/Break interrupt */ USART1_RX_TIM5_CC_IRQHandler, /* irq28 - USART1 RX / TIM1 Capture/Compare interrupt */ I2C1_SPI2_IRQHandler, }; #endif /** * @} */ #ifdef __cplusplus } #endif /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
SeanGau/Arduino_Core_STM8
cores/arduino/WInterrupts.c
/* Copyright (c) 2011-2012 Arduino. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "WInterrupts.h" #include "Arduino.h" #ifdef __cplusplus extern "C" { #endif void attachInterrupt(uint32_t pin, void (*callback)(void), uint32_t mode) { //not a valid pin if (pin > NUM_DIGITAL_PINS) { return; } PinName p = digitalPinToPinName(pin); GPIO_TypeDef *port = get_GPIO_Port(STM_PORT(p)); #if defined(STM8Sxx) EXTI_Sensitivity_TypeDef it_mode; switch (mode) { case CHANGE: it_mode = EXTI_SENSITIVITY_RISE_FALL; break; case FALLING: it_mode = EXTI_SENSITIVITY_FALL_ONLY; break; case LOW: it_mode = EXTI_SENSITIVITY_FALL_LOW; break; case RISING: case HIGH: it_mode = EXTI_SENSITIVITY_RISE_ONLY; break; default: it_mode = EXTI_SENSITIVITY_RISE_ONLY; break; } #elif defined(STM8Lxx) EXTI_Trigger_TypeDef it_mode; switch (mode) { case CHANGE: it_mode = EXTI_Trigger_Rising_Falling; break; case FALLING: it_mode = EXTI_Trigger_Falling; break; case LOW: it_mode = EXTI_Trigger_Falling_Low; break; case RISING: case HIGH: it_mode = EXTI_Trigger_Rising; break; default: it_mode = EXTI_Trigger_Rising; break; } #endif stm8_interrupt_enable(port, STM_GPIO_PIN(p), callback, it_mode); } void detachInterrupt(uint32_t pin) { //not a valid pin if (pin > NUM_DIGITAL_PINS) { return; } PinName p = digitalPinToPinName(pin); GPIO_TypeDef *port = get_GPIO_Port(STM_PORT(p)); stm8_interrupt_disable(port, STM_GPIO_PIN(p)); } #ifdef __cplusplus } #endif
SeanGau/Arduino_Core_STM8
cores/arduino/stm8/STM8_StdPeriph_Driver/stm8xx_adc.c
<reponame>SeanGau/Arduino_Core_STM8 #if defined(STM8S105) || defined(STM8S005) || defined(STM8S103) || defined(STM8S003) || \ defined(STM8S903) || defined(STM8AF626x) || defined(STM8AF622x) #include "stm8s_adc1.c" #endif #if defined(STM8S208) || defined(STM8S207) || defined (STM8S007) || defined (STM8AF52Ax) ||\ defined (STM8AF62Ax) #include "stm8s_adc2.c" #endif #if defined (STM8L15X_MD) || defined (STM8L15X_MDP) || defined (STM8L15X_HD) || defined (STM8L15X_LD) \ || defined (STM8L05X_LD_VL) || defined (STM8L05X_MD_VL) || defined (STM8L05X_HD_VL) || defined (STM8AL31_L_MD) #include "stm8l15x_adc.c" #endif
SeanGau/Arduino_Core_STM8
cores/arduino/pins_arduino.h
/* Copyright (c) 2011 Arduino. All right reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _PINS_ARDUINO_H_ #define _PINS_ARDUINO_H_ // Include board variant #include "variant.h" // Arduino digital pins alias // GPIO port (A to G) * 16 pins: 53 enum { D0, D1, D2, D3, D4, D5, D6, D7, D8, D9, D10, D11, D12, D13, D14, D15, D16, D17, D18, D19, D20, D21, D22, D23, D24, D25, D26, D27, D28, D29, D30, D31, D32, D33, D34, D35, D36, D37, D38, D39, D40, D41, D42, D43, D44, D45, D46, D47, D48, D49, D50, D51, D52, D53, D54, D55, D56, D57, D58, D59, D60, D61, D62, D63, D64, DMAX }; // Arduino analog pins // Analog pins must be contiguous to be able to loop on each value #define MAX_ANALOG_INPUTS 6 #define AEND (NUM_ANALOG_FIRST+NUM_ANALOG_INPUTS) #if NUM_ANALOG_INPUTS > 0 #define PIN_A0 NUM_ANALOG_FIRST static const uint8_t A0 = PIN_A0; #endif #if NUM_ANALOG_INPUTS > 1 #define PIN_A1 (PIN_A0 + 1) static const uint8_t A1 = PIN_A1; #endif #if NUM_ANALOG_INPUTS > 2 #define PIN_A2 (PIN_A1 + 1) static const uint8_t A2 = PIN_A2; #endif #if NUM_ANALOG_INPUTS > 3 #define PIN_A3 (PIN_A2 + 1) static const uint8_t A3 = PIN_A3; #endif #if NUM_ANALOG_INPUTS > 4 #define PIN_A4 (PIN_A3 + 1) static const uint8_t A4 = PIN_A4; #endif #if NUM_ANALOG_INPUTS > 5 #define PIN_A5 (PIN_A4 + 1) static const uint8_t A5 = PIN_A5; #endif // Default for Arduino connector compatibility // SPI Definitions #ifndef PIN_SPI_SS #define PIN_SPI_SS 10 #endif #ifndef PIN_SPI_SS1 #define PIN_SPI_SS1 4 #endif #ifndef PIN_SPI_SS2 #define PIN_SPI_SS2 7 #endif #ifndef PIN_SPI_SS3 #define PIN_SPI_SS3 8 #endif #ifndef PIN_SPI_MOSI #define PIN_SPI_MOSI 11 #endif #ifndef PIN_SPI_MISO #define PIN_SPI_MISO 12 #endif #ifndef PIN_SPI_SCK #define PIN_SPI_SCK 13 #endif static const uint8_t SS = PIN_SPI_SS; static const uint8_t SS1 = PIN_SPI_SS1; static const uint8_t SS2 = PIN_SPI_SS2; static const uint8_t SS3 = PIN_SPI_SS3; static const uint8_t MOSI = PIN_SPI_MOSI; static const uint8_t MISO = PIN_SPI_MISO; static const uint8_t SCK = PIN_SPI_SCK; // I2C Definitions #ifndef PIN_WIRE_SDA #define PIN_WIRE_SDA 14 #endif #ifndef PIN_WIRE_SCL #define PIN_WIRE_SCL 15 #endif static const uint8_t SDA = PIN_WIRE_SDA; static const uint8_t SCL = PIN_WIRE_SCL; #ifdef __cplusplus extern "C" { #endif #define NOT_AN_INTERRUPT NC // -1 // Convert a digital pin number Dxx to a PinName PX_n // Note: Analog pin is also a digital pin. #define digitalPinToPinName(p) (((uint32_t)p < NUM_DIGITAL_PINS) ? digitalPin[p] : NC) // Convert a PinName PX_n to a digital pin number uint32_t pinNametoDigitalPin(PinName p); // Convert an analog pin number to a digital pin number // Used by analogRead api to have A0 == 0 #define analogInputToDigitalPin(p) (((uint32_t)p < NUM_ANALOG_INPUTS) ? (p+A0) : p) // Convert an analog pin number Axx to a PinName PX_n #define analogInputToPinName(p) (digitalPinToPinName(analogInputToDigitalPin(p))) // All pins could manage EXTI #define digitalPinToInterrupt(p) (digitalPinIsValid(p) ? p : NOT_AN_INTERRUPT) #define digitalPinHasI2C(p) (pin_in_pinmap(digitalPinToPinName(p), PinMap_I2C_SDA) ||\ pin_in_pinmap(digitalPinToPinName(p), PinMap_I2C_SCL)) #define digitalPinHasPWM(p) (pin_in_pinmap(digitalPinToPinName(p), PinMap_PWM)) #define digitalPinHasSerial(p) (pin_in_pinmap(digitalPinToPinName(p), PinMap_UART_RX) ||\ pin_in_pinmap(digitalPinToPinName(p), PinMap_UART_TX)) #define digitalPinHasSPI(p) (pin_in_pinmap(digitalPinToPinName(p), PinMap_SPI_MOSI) ||\ pin_in_pinmap(digitalPinToPinName(p), PinMap_SPI_MISO) ||\ pin_in_pinmap(digitalPinToPinName(p), PinMap_SPI_SCLK) ||\ pin_in_pinmap(digitalPinToPinName(p), PinMap_SPI_SSEL)) #define digitalPinToPort(p) (get_GPIO_Port(STM_PORT(digitalPinToPinName(p)))) #define digitalPinToBitMask(p) (STM_GPIO_PIN(digitalPinToPinName(p))) #define analogInPinToBit(p) (STM_PIN(digitalPinToPinName(p))) #define portOutputRegister(P) (&(P->ODR)) #define portInputRegister(P) (&(P->IDR)) #define portConfigRegister(P) (portModeRegister(P)) #define digitalPinIsValid(p) (digitalPinToPinName(p) != NC) // As some pin could be duplicated in digitalPin[] // return first occurence of linked PinName (PYx) #define digitalPinFirstOccurence(p) (pinNametoDigitalPin(digitalPinToPinName(p))) // Specific for Firmata. As some pins could be duplicated, // ensure 'p' is not one of the serial pins #if defined(PIN_SERIAL_RX) && defined(PIN_SERIAL_TX) #define pinIsSerial(p) ((digitalPinFirstOccurence(p) == PIN_SERIAL_RX) ||\ (digitalPinFirstOccurence(p) == PIN_SERIAL_TX)) #endif #ifdef __cplusplus } #endif // Default Definitions, could be redefined in variant.h #ifndef ADC_RESOLUTION #define ADC_RESOLUTION 12 #endif #ifndef DACC_RESOLUTION #define DACC_RESOLUTION 12 #endif #ifndef PWM_RESOLUTION #define PWM_RESOLUTION 8 #endif #ifndef PWM_FREQUENCY #define PWM_FREQUENCY 1000 #endif #ifndef PWM_MAX_DUTY_CYCLE #define PWM_MAX_DUTY_CYCLE 255 #endif #endif /*_PINS_ARDUINO_H_*/
SeanGau/Arduino_Core_STM8
cores/arduino/stm8/interrupt.c
<filename>cores/arduino/stm8/interrupt.c /** ****************************************************************************** * @file interrupt.c * @author WI6LABS * @version V1.0.0 * @date 16-September-2016 * @brief provide an interface to enable/disable interruptions * ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ #include "stm8_def.h" #include "interrupt.h" #ifdef __cplusplus extern "C" { #endif /** * @} */ /** @addtogroup stm8sxx_System_Private_TypesDefinitions * @{ */ typedef struct { EXTI_Port_TypeDef EXTI_port; GPIO_Pin_TypeDef pin; uint8_t current_level; #if defined(STM8Sxx) EXTI_Sensitivity_TypeDef EXTI_mode; #elif defined(STM8Lxx) GPIO_TypeDef *port_IT; EXTI_Pin_TypeDef EXTI_pin; EXTI_Trigger_TypeDef EXTI_mode; #endif void (*callback)(void); } gpio_irq_conf_str; /** * @} */ /** @addtogroup stm8sxx_System_Private_Defines * @{ */ #define NB_EXTI ((uint8_t)16) /*As this port are not usable with exti, use dummy values*/ #define EXTI_Port_A_Int ((uint8_t)0xFD) #define EXTI_Port_C_Int ((uint8_t)0xFE) /** @addtogroup stm8sxx_System_Private_Macros * @{ */ /** * @} */ /** @addtogroup stm8sxx_System_Private_Variables * @{ */ static gpio_irq_conf_str gpio_irq_conf[NB_EXTI]; /** * @} */ /** @addtogroup stm8sxx_System_Private_FunctionPrototypes * @{ */ static uint8_t get_pin_id(GPIO_TypeDef *port, GPIO_Pin_TypeDef pin, uint8_t init); /** * @} */ /** * @brief This function returns the pin ID function of the PIN definition * @param port : one of the gpio port * @param pin : one of the gpio pin * @retval None */ static uint8_t get_pin_id(GPIO_TypeDef *port, GPIO_Pin_TypeDef pin, uint8_t init) { uint8_t id = NC; uint8_t i = 0; EXTI_Port_TypeDef EXTI_port = 0xFF; #if defined(STM8Sxx) if (port == GPIOA) { EXTI_port = EXTI_PORT_GPIOA; } else if (port == GPIOB) { EXTI_port = EXTI_PORT_GPIOB; } else if (port == GPIOC) { EXTI_port = EXTI_PORT_GPIOC; } else if (port == GPIOD) { EXTI_port = EXTI_PORT_GPIOD; } else if (port == GPIOE) { EXTI_port = EXTI_PORT_GPIOE; } else { return id; } #elif defined(STM8Lxx) EXTI_Pin_TypeDef EXTI_pin; if (port == GPIOA) { EXTI_port = EXTI_Port_A_Int; } else if (port == GPIOB) { EXTI_port = EXTI_Port_B; } else if (port == GPIOC) { EXTI_port = EXTI_Port_C_Int; } else if (port == GPIOD) { EXTI_port = EXTI_Port_D; } else if (port == GPIOE) { EXTI_port = EXTI_Port_E; } else if (port == GPIOF) { EXTI_port = EXTI_Port_F; } else if (port == GPIOG) { EXTI_port = EXTI_Port_G; } else if (port == GPIOH) { EXTI_port = EXTI_Port_H; } else { return id; } if (pin == GPIO_Pin_0) { EXTI_pin = EXTI_Pin_0; } else if (pin == GPIO_Pin_1) { EXTI_pin = EXTI_Pin_1; } else if (pin == GPIO_Pin_2) { EXTI_pin = EXTI_Pin_2; } else if (pin == GPIO_Pin_3) { EXTI_pin = EXTI_Pin_3; } else if (pin == GPIO_Pin_4) { EXTI_pin = EXTI_Pin_4; } else if (pin == GPIO_Pin_5) { EXTI_pin = EXTI_Pin_5; } else if (pin == GPIO_Pin_6) { EXTI_pin = EXTI_Pin_6; } else if (pin == GPIO_Pin_7) { EXTI_pin = EXTI_Pin_7; } else { return id; } #endif for (id = 0; id < NB_EXTI; id++) { if ((gpio_irq_conf[id].EXTI_port == EXTI_port) && (gpio_irq_conf[id].pin == pin)) { id = i; break; } else if ((init == 1)&&(gpio_irq_conf[id].pin == 0)) { gpio_irq_conf[id].EXTI_port = EXTI_port; gpio_irq_conf[id].pin = pin; gpio_irq_conf[id].callback = 0; #ifdef STM8Lxx gpio_irq_conf[id].port_IT = port; gpio_irq_conf[id].EXTI_pin = EXTI_pin; #endif break; } } return id; } /** * @brief This function enable the interruption on the selected port/pin * @param port : one of the gpio port * @param pin : one of the gpio pin **@param callback : callback to call when the interrupt falls * @param mode : one of the supported interrupt mode defined in stm32_hal_gpio * @retval None */ #if defined(STM8Sxx) void stm8_interrupt_enable(GPIO_TypeDef *port, GPIO_Pin_TypeDef pin, void (*callback)(void), EXTI_Sensitivity_TypeDef EXTI_mode) #elif defined(STM8Lxx) void stm8_interrupt_enable(GPIO_TypeDef *port, GPIO_Pin_TypeDef pin, void (*callback)(void), EXTI_Trigger_TypeDef EXTI_mode) #endif { GPIO_Mode_TypeDef GPIO_mode; uint8_t id = get_pin_id(port, pin, 1); if (id == NC) { return; } gpio_irq_conf[id].callback = callback; gpio_irq_conf[id].EXTI_mode = EXTI_mode; // Enable and set EXTI Interrupt disableInterrupts(); #if defined(STM8Sxx) GPIO_Init(port, pin, GPIO_MODE_IN_PU_IT); gpio_irq_conf[id].current_level = GPIO_ReadInputPin(port, pin); EXTI_SetExtIntSensitivity(gpio_irq_conf[id].EXTI_port, EXTI_SENSITIVITY_RISE_FALL/*EXTI_mode*/); #elif defined(STM8Lxx) GPIO_Init(port, pin, GPIO_Mode_In_PU_IT); gpio_irq_conf[id].current_level = GPIO_ReadInputDataBit(port, pin); if(EXTI_GetPinSensitivity(gpio_irq_conf[id].EXTI_pin) != EXTI_Trigger_Rising_Falling) { EXTI_SetPinSensitivity(gpio_irq_conf[id].EXTI_pin, EXTI_Trigger_Rising_Falling); } #endif enableInterrupts(); #if defined(STM8Sxx) gpio_irq_conf[id].current_level = GPIO_ReadInputPin(port, pin); #elif defined(STM8Lxx) gpio_irq_conf[id].current_level = GPIO_ReadInputDataBit(port, pin); #endif } /** * @brief This function disable the interruption on the selected port/pin * @param port : one of the gpio port * @param pin : one of the gpio pin * @retval None */ void stm8_interrupt_disable(GPIO_TypeDef *port, GPIO_Pin_TypeDef pin) { GPIO_Mode_TypeDef GPIO_mode = (GPIO_Mode_TypeDef)0; uint8_t id = get_pin_id(port, pin, 0); if (id == NC) { return; } gpio_irq_conf[id].EXTI_port = (EXTI_Port_TypeDef)0; gpio_irq_conf[id].pin = (GPIO_Pin_TypeDef)0; #if defined(STM8Sxx) gpio_irq_conf[id].EXTI_mode = (EXTI_Sensitivity_TypeDef)0; #elif defined(STM8Lxx) gpio_irq_conf[id].EXTI_mode = (EXTI_Trigger_TypeDef)0; #endif gpio_irq_conf[id].callback = 0; #if defined(STM8Sxx) if ((port->CR1 & pin) == pin) { GPIO_mode = GPIO_MODE_IN_PU_NO_IT; } else { GPIO_mode = GPIO_MODE_IN_FL_NO_IT; } #elif defined(STM8Lxx) if ((port->CR1 & pin) == pin) { GPIO_mode = GPIO_Mode_In_PU_No_IT; } else { GPIO_mode = GPIO_Mode_In_FL_No_IT; } #endif GPIO_Init(port, pin, GPIO_mode); } /** * @brief This function his called by EXTI interrupt * @param EXTI_port : EXTI_Port_TypeDef * @retval None */ #if defined(STM8Sxx) void GPIO_EXTI_Callback(EXTI_Port_TypeDef EXTI_port) { #endif #if defined(STM8Lxx) void GPIO_EXTI_Callback(EXTI_IT_TypeDef EXTI_port_pin) { #endif GPIO_TypeDef *port; GPIO_Pin_TypeDef pin; BitStatus status = RESET; uint8_t i = 0; uint8_t old_level = SET; #if defined(STM8Sxx) if (EXTI_port == EXTI_PORT_GPIOA) { port = GPIOA; } else if (EXTI_port == EXTI_PORT_GPIOB) { port = GPIOB; } else if (EXTI_port == EXTI_PORT_GPIOC) { port = GPIOC; } else if (EXTI_port == EXTI_PORT_GPIOD) { port = GPIOD; } else if (EXTI_port == EXTI_PORT_GPIOE) { port = GPIOE; } else { return; } for (i = 0; i < NB_EXTI; i++) { if (gpio_irq_conf[i].EXTI_port == EXTI_port) { status = RESET; old_level = gpio_irq_conf[i].current_level; gpio_irq_conf[i].current_level = GPIO_ReadInputPin(port, gpio_irq_conf[i].pin); switch (gpio_irq_conf[i].EXTI_mode) { case EXTI_SENSITIVITY_FALL_LOW: case EXTI_SENSITIVITY_FALL_ONLY: if((old_level != RESET) && (gpio_irq_conf[i].current_level == RESET)) { status = SET; } break; case EXTI_SENSITIVITY_RISE_ONLY: if((old_level == RESET) && (gpio_irq_conf[i].current_level != RESET)) { status = SET; } break; case EXTI_SENSITIVITY_RISE_FALL: status = SET; break; default: break; } if ((gpio_irq_conf[i].callback != 0) && (status == SET)) { gpio_irq_conf[i].callback(); } } } #endif #if defined(STM8Lxx) EXTI_Port_TypeDef EXTI_port; EXTI_Pin_TypeDef EXTI_pin; EXTI_ClearITPendingBit(EXTI_port_pin); if (EXTI_port_pin == EXTI_IT_Pin0) { pin = GPIO_Pin_0; EXTI_pin = EXTI_Pin_0; } else if (EXTI_port_pin == EXTI_IT_Pin1) { pin = GPIO_Pin_1; EXTI_pin = EXTI_Pin_1; } else if (EXTI_port_pin == EXTI_IT_Pin2) { pin = GPIO_Pin_2; EXTI_pin = EXTI_Pin_2; } else if (EXTI_port_pin == EXTI_IT_Pin3) { pin = GPIO_Pin_3; EXTI_pin = EXTI_Pin_3; } else if (EXTI_port_pin == EXTI_IT_Pin4) { pin = GPIO_Pin_4; EXTI_pin = EXTI_Pin_4; } else if (EXTI_port_pin == EXTI_IT_Pin5) { pin = GPIO_Pin_5; EXTI_pin = EXTI_Pin_5; } else if (EXTI_port_pin == EXTI_IT_Pin6) { pin = GPIO_Pin_6; EXTI_pin = EXTI_Pin_6; } else if (EXTI_port_pin == EXTI_IT_Pin7) { pin = GPIO_Pin_7; EXTI_pin = EXTI_Pin_7; } else { return; } for (i = 0; i < NB_EXTI; i++) { if (gpio_irq_conf[i].EXTI_pin == EXTI_pin) { status = RESET; old_level = gpio_irq_conf[i].current_level; gpio_irq_conf[i].current_level = GPIO_ReadInputDataBit(gpio_irq_conf[i].port_IT, gpio_irq_conf[i].pin); switch (gpio_irq_conf[i].EXTI_mode) { case EXTI_Trigger_Falling_Low: case EXTI_Trigger_Falling: if((old_level != RESET) && (gpio_irq_conf[i].current_level == RESET)) { status = SET; } break; case EXTI_Trigger_Rising: if((old_level == RESET) && (gpio_irq_conf[i].current_level != RESET)) { status = SET; } break; case EXTI_Trigger_Rising_Falling: status = SET; break; default: break; } if ((gpio_irq_conf[i].callback != 0) && (status == SET)) { gpio_irq_conf[i].callback(); } } } #endif } /** * @} */ /** * @} */ /** * @} */ #ifdef __cplusplus } #endif /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
SeanGau/Arduino_Core_STM8
cores/arduino/stm8/clock.c
<filename>cores/arduino/stm8/clock.c /** ****************************************************************************** * @file clock.c * @author WI6LABS * @version V1.0.0 * @date * @brief provide clock services for time purpose * ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ #include "stm8_def.h" #include "clock.h" #include "timer.h" #ifdef __cplusplus extern "C" { #endif static volatile uint32_t g_current_ms = 1; static volatile uint8_t g_count_ms = 0; static void TimerDelay_PeriodElapsedCallback(timer_id_e timer_id); /** * @brief Function called wto read the current micro second * @param None * @retval None */ uint32_t GetCurrentMicro(void) { uint32_t us; uint8_t cc; cc = (uint8_t) _asm("push cc\n sim\n pop a"); us = (uint32_t)TIM4_GetCounter() + (g_count_ms * 249); us += g_current_ms * 1000; _asm("push a\n pop cc", cc); return us; } /** * @brief Function called wto read the current millisecond * @param None * @retval None */ uint32_t GetCurrentMilli(void) { uint32_t ms; uint8_t cc; cc = (uint8_t) _asm("push cc\n sim\n pop a"); ms = g_current_ms; _asm("push a\n pop cc", cc); return ms; } /** * @brief This function configures the source of the time base. * @param None * @retval None */ void InitDelayTimer(void) { /*configure TIMER to get the microsecond precision time. 1MhZ is applied to the timer. Timer will count until 1ms ends*/ /* Currently the timer count until 250 us because TIM4 is a 8 bits timer*/ attachIntHandle(TIM4_E, TimerDelay_PeriodElapsedCallback); #if defined(STM8Sxx) TimerHandleInit(TIM4_E, 250, TIM4_PRESCALER_16); #elif defined(STM8Lxx) TimerHandleInit(TIM4_E, 250, TIM4_Prescaler_16); #endif } /** * @brief TIM5 period elapsed callback in non blocking mode * @param None * @retval None */ static void TimerDelay_PeriodElapsedCallback(timer_id_e timer_id) { g_count_ms++; if (g_count_ms >= 4) { g_current_ms++; g_count_ms = 0; } } #ifdef __cplusplus } #endif /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
SeanGau/Arduino_Core_STM8
cores/arduino/stm8/STM8_StdPeriph_Driver/stm8xx_uart4.c
<filename>cores/arduino/stm8/STM8_StdPeriph_Driver/stm8xx_uart4.c #if !defined(NO_HWSERIAL) #if defined(STM8AF622x) #include "stm8s_uart4.c" #endif #endif /* !NO_HWSERIAL */
SeanGau/Arduino_Core_STM8
cores/arduino/stm8/digital_io.c
<gh_stars>100-1000 /** ****************************************************************************** * @file digital_io.c * @author WI6LABS * @version V1.0.0 * @date 16-September-2016 * @brief Provide an interface to configure hw ios * ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ #include "digital_io.h" #include "stm8_def.h" #include "hw_config.h" #ifdef __cplusplus extern "C" { #endif /** * @brief This function initialize the IO * @param port : one of the gpio port * @param pin : one of the gpio pin * @param mode : one of the gpio mode (cf stm8s_gpio.h) * @retval None */ void digital_io_init(PinName pin, GPIO_Mode_TypeDef mode, uint32_t pull) { GPIO_TypeDef *port = get_GPIO_Port(STM_PORT(pin)); GPIO_Init(port, STM_GPIO_PIN(pin), mode); } /** * @brief This function set a value to an IO * @param port : one of the gpio port * @param pin : one of the gpio pin * @param val : 0 to set to low, any other value to set to high * @retval None */ void digital_io_write(GPIO_TypeDef *port, GPIO_Pin_TypeDef pin, uint32_t val) { #if defined(STM8Sxx) if (val) { GPIO_WriteHigh(port, pin); } else { GPIO_WriteLow(port, pin); } #elif defined(STM8Lxx) if (val) { GPIO_SetBits(port, pin); } else { GPIO_ResetBits(port, pin); } #endif } /** * @brief This function set a value to an IO * @param port : one of the gpio port * @param pin : one of the gpio pin * @retval The pin state (LOW or HIGH) */ uint32_t digital_io_read(GPIO_TypeDef *port, GPIO_Pin_TypeDef pin) { #if defined(STM8Sxx) return (uint32_t)GPIO_ReadInputPin(port, pin); #elif defined(STM8Lxx) return (uint32_t)GPIO_ReadInputDataBit(port, pin); #endif } #ifdef __cplusplus } #endif /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
SeanGau/Arduino_Core_STM8
system/Drivers/STM8Sxx_StdPeriph_Driver/src/stm8s_tim5.c
/** ****************************************************************************** * @file stm8s_tim5.c * @author MCD Application Team * @version V2.3.0 * @date 16-June-2017 * @brief This file contains all the functions for the TIM5 peripheral. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT 2014 STMicroelectronics</center></h2> * * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License"); * You may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.st.com/software_license_agreement_liberty_v2 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm8s_tim5.h" /** @addtogroup STM8S_StdPeriph_Driver * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ static void TI1_Config(uint8_t TIM5_ICPolarity, uint8_t TIM5_ICSelection, uint8_t TIM5_ICFilter); static void TI2_Config(uint8_t TIM5_ICPolarity, uint8_t TIM5_ICSelection, uint8_t TIM5_ICFilter); static void TI3_Config(uint8_t TIM5_ICPolarity, uint8_t TIM5_ICSelection, uint8_t TIM5_ICFilter); /** * @addtogroup TIM5_Public_Functions * @{ */ /** * @brief Deinitializes the TIM5 peripheral registers to their default reset values. * @param None * @retval None */ void TIM5_DeInit(void) { TIM5->CR1 = (uint8_t)TIM5_CR1_RESET_VALUE; TIM5->CR2 = TIM5_CR2_RESET_VALUE; TIM5->SMCR = TIM5_SMCR_RESET_VALUE; TIM5->IER = (uint8_t)TIM5_IER_RESET_VALUE; TIM5->SR2 = (uint8_t)TIM5_SR2_RESET_VALUE; /* Disable channels */ TIM5->CCER1 = (uint8_t)TIM5_CCER1_RESET_VALUE; TIM5->CCER2 = (uint8_t)TIM5_CCER2_RESET_VALUE; /* Then reset channel registers: it also works if lock level is equal to 2 or 3 */ TIM5->CCER1 = (uint8_t)TIM5_CCER1_RESET_VALUE; TIM5->CCER2 = (uint8_t)TIM5_CCER2_RESET_VALUE; TIM5->CCMR1 = (uint8_t)TIM5_CCMR1_RESET_VALUE; TIM5->CCMR2 = (uint8_t)TIM5_CCMR2_RESET_VALUE; TIM5->CCMR3 = (uint8_t)TIM5_CCMR3_RESET_VALUE; TIM5->CNTRH = (uint8_t)TIM5_CNTRH_RESET_VALUE; TIM5->CNTRL = (uint8_t)TIM5_CNTRL_RESET_VALUE; TIM5->PSCR = (uint8_t)TIM5_PSCR_RESET_VALUE; TIM5->ARRH = (uint8_t)TIM5_ARRH_RESET_VALUE; TIM5->ARRL = (uint8_t)TIM5_ARRL_RESET_VALUE; TIM5->CCR1H = (uint8_t)TIM5_CCR1H_RESET_VALUE; TIM5->CCR1L = (uint8_t)TIM5_CCR1L_RESET_VALUE; TIM5->CCR2H = (uint8_t)TIM5_CCR2H_RESET_VALUE; TIM5->CCR2L = (uint8_t)TIM5_CCR2L_RESET_VALUE; TIM5->CCR3H = (uint8_t)TIM5_CCR3H_RESET_VALUE; TIM5->CCR3L = (uint8_t)TIM5_CCR3L_RESET_VALUE; TIM5->SR1 = (uint8_t)TIM5_SR1_RESET_VALUE; } /** * @brief Initializes the TIM5 Time Base Unit according to the specified parameters. * @param TIM5_Prescaler specifies the Prescaler from TIM5_Prescaler_TypeDef. * @param TIM5_Period specifies the Period value. * @retval None */ void TIM5_TimeBaseInit( TIM5_Prescaler_TypeDef TIM5_Prescaler, uint16_t TIM5_Period) { /* Set the Prescaler value */ TIM5->PSCR = (uint8_t)(TIM5_Prescaler); /* Set the Autoreload value */ TIM5->ARRH = (uint8_t)(TIM5_Period >> 8) ; TIM5->ARRL = (uint8_t)(TIM5_Period); } /** * @brief Initializes the TIM5 Channel1 according to the specified parameters. * @param TIM5_OCMode specifies the Output Compare mode from @ref TIM5_OCMode_TypeDef. * @param TIM5_OutputState specifies the Output State from @ref TIM5_OutputState_TypeDef. * @param TIM5_Pulse specifies the Pulse width value. * @param TIM5_OCPolarity specifies the Output Compare Polarity from @ref TIM5_OCPolarity_TypeDef. * @retval None */ void TIM5_OC1Init(TIM5_OCMode_TypeDef TIM5_OCMode, TIM5_OutputState_TypeDef TIM5_OutputState, uint16_t TIM5_Pulse, TIM5_OCPolarity_TypeDef TIM5_OCPolarity) { /* Check the parameters */ assert_param(IS_TIM5_OC_MODE_OK(TIM5_OCMode)); assert_param(IS_TIM5_OUTPUT_STATE_OK(TIM5_OutputState)); assert_param(IS_TIM5_OC_POLARITY_OK(TIM5_OCPolarity)); /* Disable the Channel 1: Reset the CCE Bit, Set the Output State , the Output Polarity */ TIM5->CCER1 &= (uint8_t)(~( TIM5_CCER1_CC1E | TIM5_CCER1_CC1P)); /* Set the Output State & Set the Output Polarity */ TIM5->CCER1 |= (uint8_t)((uint8_t)(TIM5_OutputState & TIM5_CCER1_CC1E )| (uint8_t)(TIM5_OCPolarity & TIM5_CCER1_CC1P)); /* Reset the Output Compare Bits & Set the Output Compare Mode */ TIM5->CCMR1 = (uint8_t)((uint8_t)(TIM5->CCMR1 & (uint8_t)(~TIM5_CCMR_OCM)) | (uint8_t)TIM5_OCMode); /* Set the Pulse value */ TIM5->CCR1H = (uint8_t)(TIM5_Pulse >> 8); TIM5->CCR1L = (uint8_t)(TIM5_Pulse); } /** * @brief Initializes the TIM5 Channel2 according to the specified parameters. * @param TIM5_OCMode specifies the Output Compare mode from @ref TIM5_OCMode_TypeDef. * @param TIM5_OutputState specifies the Output State from @ref TIM5_OutputState_TypeDef. * @param TIM5_Pulse specifies the Pulse width value. * @param TIM5_OCPolarity specifies the Output Compare Polarity from @ref TIM5_OCPolarity_TypeDef. * @retval None */ void TIM5_OC2Init(TIM5_OCMode_TypeDef TIM5_OCMode, TIM5_OutputState_TypeDef TIM5_OutputState, uint16_t TIM5_Pulse, TIM5_OCPolarity_TypeDef TIM5_OCPolarity) { /* Check the parameters */ assert_param(IS_TIM5_OC_MODE_OK(TIM5_OCMode)); assert_param(IS_TIM5_OUTPUT_STATE_OK(TIM5_OutputState)); assert_param(IS_TIM5_OC_POLARITY_OK(TIM5_OCPolarity)); /* Disable the Channel 1: Reset the CCE Bit, Set the Output State , the Output Polarity */ TIM5->CCER1 &= (uint8_t)(~( TIM5_CCER1_CC2E | TIM5_CCER1_CC2P )); /* Set the Output State & Set the Output Polarity */ TIM5->CCER1 |= (uint8_t)((uint8_t)(TIM5_OutputState & TIM5_CCER1_CC2E )| \ (uint8_t)(TIM5_OCPolarity & TIM5_CCER1_CC2P)); /* Reset the Output Compare Bits & Set the Output Compare Mode */ TIM5->CCMR2 = (uint8_t)((uint8_t)(TIM5->CCMR2 & (uint8_t)(~TIM5_CCMR_OCM)) | (uint8_t)TIM5_OCMode); /* Set the Pulse value */ TIM5->CCR2H = (uint8_t)(TIM5_Pulse >> 8); TIM5->CCR2L = (uint8_t)(TIM5_Pulse); } /** * @brief Initializes the TIM5 Channel3 according to the specified parameters. * @param TIM5_OCMode specifies the Output Compare mode from @ref TIM5_OCMode_TypeDef. * @param TIM5_OutputState specifies the Output State from @ref TIM5_OutputState_TypeDef. * @param TIM5_Pulse specifies the Pulse width value. * @param TIM5_OCPolarity specifies the Output Compare Polarity from @ref TIM5_OCPolarity_TypeDef. * @retval None */ void TIM5_OC3Init(TIM5_OCMode_TypeDef TIM5_OCMode, TIM5_OutputState_TypeDef TIM5_OutputState, uint16_t TIM5_Pulse, TIM5_OCPolarity_TypeDef TIM5_OCPolarity) { /* Check the parameters */ assert_param(IS_TIM5_OC_MODE_OK(TIM5_OCMode)); assert_param(IS_TIM5_OUTPUT_STATE_OK(TIM5_OutputState)); assert_param(IS_TIM5_OC_POLARITY_OK(TIM5_OCPolarity)); /* Disable the Channel 1: Reset the CCE Bit, Set the Output State, the Output Polarity */ TIM5->CCER2 &= (uint8_t)(~( TIM5_CCER2_CC3E | TIM5_CCER2_CC3P)); /* Set the Output State & Set the Output Polarity */ TIM5->CCER2 |= (uint8_t)((uint8_t)(TIM5_OutputState & TIM5_CCER2_CC3E )| (uint8_t)(TIM5_OCPolarity & TIM5_CCER2_CC3P )); /* Reset the Output Compare Bits & Set the Output Compare Mode */ TIM5->CCMR3 = (uint8_t)((uint8_t)(TIM5->CCMR3 & (uint8_t)(~TIM5_CCMR_OCM)) | (uint8_t)TIM5_OCMode); /* Set the Pulse value */ TIM5->CCR3H = (uint8_t)(TIM5_Pulse >> 8); TIM5->CCR3L = (uint8_t)(TIM5_Pulse); } /** * @brief Initializes the TIM5 peripheral according to the specified parameters. * @param TIM5_Channel specifies the Input Capture Channel from @ref TIM5_Channel_TypeDef. * @param TIM5_ICPolarity specifies the Input Capture Polarity from @ref TIM5_ICPolarity_TypeDef. * @param TIM5_ICSelection specifies theInput Capture Selection from @ref TIM5_ICSelection_TypeDef. * @param TIM5_ICPrescaler specifies the Input Capture Prescaler from @ref TIM5_ICPSC_TypeDef. * @param TIM5_ICFilter specifies the Input Capture Filter value (value can be an integer from 0x00 to 0x0F). * @retval None */ void TIM5_ICInit(TIM5_Channel_TypeDef TIM5_Channel, TIM5_ICPolarity_TypeDef TIM5_ICPolarity, TIM5_ICSelection_TypeDef TIM5_ICSelection, TIM5_ICPSC_TypeDef TIM5_ICPrescaler, uint8_t TIM5_ICFilter) { /* Check the parameters */ assert_param(IS_TIM5_CHANNEL_OK(TIM5_Channel)); assert_param(IS_TIM5_IC_POLARITY_OK(TIM5_ICPolarity)); assert_param(IS_TIM5_IC_SELECTION_OK(TIM5_ICSelection)); assert_param(IS_TIM5_IC_PRESCALER_OK(TIM5_ICPrescaler)); assert_param(IS_TIM5_IC_FILTER_OK(TIM5_ICFilter)); if (TIM5_Channel == TIM5_CHANNEL_1) { /* TI1 Configuration */ TI1_Config((uint8_t)TIM5_ICPolarity, (uint8_t)TIM5_ICSelection, (uint8_t)TIM5_ICFilter); /* Set the Input Capture Prescaler value */ TIM5_SetIC1Prescaler(TIM5_ICPrescaler); } else if (TIM5_Channel == TIM5_CHANNEL_2) { /* TI2 Configuration */ TI2_Config((uint8_t)TIM5_ICPolarity, (uint8_t)TIM5_ICSelection, (uint8_t)TIM5_ICFilter); /* Set the Input Capture Prescaler value */ TIM5_SetIC2Prescaler(TIM5_ICPrescaler); } else { /* TI3 Configuration */ TI3_Config((uint8_t)TIM5_ICPolarity, (uint8_t)TIM5_ICSelection, (uint8_t)TIM5_ICFilter); /* Set the Input Capture Prescaler value */ TIM5_SetIC3Prescaler(TIM5_ICPrescaler); } } /** * @brief Configures the TIM5 peripheral in PWM Input Mode according to the specified parameters. * @param TIM5_Channel specifies the Input Capture Channel from @ref TIM5_Channel_TypeDef. * @param TIM5_ICPolarity specifies the Input Capture Polarity from @ref TIM5_ICPolarity_TypeDef. * @param TIM5_ICSelection specifies theInput Capture Selection from @ref TIM5_ICSelection_TypeDef. * @param TIM5_ICPrescaler specifies the Input Capture Prescaler from @ref TIM5_ICPSC_TypeDef. * @param TIM5_ICFilter specifies the Input Capture Filter value (value can be an integer from 0x00 to 0x0F). * @retval None */ void TIM5_PWMIConfig(TIM5_Channel_TypeDef TIM5_Channel, TIM5_ICPolarity_TypeDef TIM5_ICPolarity, TIM5_ICSelection_TypeDef TIM5_ICSelection, TIM5_ICPSC_TypeDef TIM5_ICPrescaler, uint8_t TIM5_ICFilter) { uint8_t icpolarity = (uint8_t)TIM5_ICPOLARITY_RISING; uint8_t icselection = (uint8_t)TIM5_ICSELECTION_DIRECTTI; /* Check the parameters */ assert_param(IS_TIM5_PWMI_CHANNEL_OK(TIM5_Channel)); assert_param(IS_TIM5_IC_POLARITY_OK(TIM5_ICPolarity)); assert_param(IS_TIM5_IC_SELECTION_OK(TIM5_ICSelection)); assert_param(IS_TIM5_IC_PRESCALER_OK(TIM5_ICPrescaler)); /* Select the Opposite Input Polarity */ if (TIM5_ICPolarity != TIM5_ICPOLARITY_FALLING) { icpolarity = (uint8_t)TIM5_ICPOLARITY_FALLING; } else { icpolarity = (uint8_t)TIM5_ICPOLARITY_RISING; } /* Select the Opposite Input */ if (TIM5_ICSelection == TIM5_ICSELECTION_DIRECTTI) { icselection = (uint8_t)TIM5_ICSELECTION_INDIRECTTI; } else { icselection = (uint8_t)TIM5_ICSELECTION_DIRECTTI; } if (TIM5_Channel == TIM5_CHANNEL_1) { /* TI1 Configuration */ TI1_Config((uint8_t)TIM5_ICPolarity, (uint8_t)TIM5_ICSelection, (uint8_t)TIM5_ICFilter); /* Set the Input Capture Prescaler value */ TIM5_SetIC1Prescaler(TIM5_ICPrescaler); /* TI2 Configuration */ TI2_Config((uint8_t)icpolarity, (uint8_t)icselection, (uint8_t)TIM5_ICFilter); /* Set the Input Capture Prescaler value */ TIM5_SetIC2Prescaler(TIM5_ICPrescaler); } else { /* TI2 Configuration */ TI2_Config((uint8_t)TIM5_ICPolarity, (uint8_t)TIM5_ICSelection, (uint8_t)TIM5_ICFilter); /* Set the Input Capture Prescaler value */ TIM5_SetIC2Prescaler(TIM5_ICPrescaler); /* TI1 Configuration */ TI1_Config((uint8_t)icpolarity, (uint8_t)icselection, (uint8_t)TIM5_ICFilter); /* Set the Input Capture Prescaler value */ TIM5_SetIC1Prescaler(TIM5_ICPrescaler); } } /** * @brief Enables or disables the TIM5 peripheral. * @param NewState new state of the TIM5 peripheral.This parameter can * be ENABLE or DISABLE. * @retval None */ void TIM5_Cmd(FunctionalState NewState) { /* Check the parameters */ assert_param(IS_FUNCTIONALSTATE_OK(NewState)); /* set or Reset the CEN Bit */ if (NewState != DISABLE) { TIM5->CR1 |= TIM5_CR1_CEN ; } else { TIM5->CR1 &= (uint8_t)(~TIM5_CR1_CEN) ; } } /** * @brief Enables or disables the specified TIM5 interrupts. * @param NewState new state of the TIM5 peripheral. * This parameter can be: ENABLE or DISABLE. * @param TIM5_IT specifies the TIM5 interrupts sources to be enabled or disabled. * This parameter can be any combination of the following values: * - TIM5_IT_UPDATE: TIM5 update Interrupt source * - TIM5_IT_CC1: TIM5 Capture Compare 1 Interrupt source * - TIM5_IT_CC2: TIM5 Capture Compare 2 Interrupt source * - TIM5_IT_CC3: TIM5 Capture Compare 3 Interrupt source * @param NewState new state of the TIM5 peripheral. * @retval None */ void TIM5_ITConfig(TIM5_IT_TypeDef TIM5_IT, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_TIM5_IT_OK(TIM5_IT)); assert_param(IS_FUNCTIONALSTATE_OK(NewState)); if (NewState != DISABLE) { /* Enable the Interrupt sources */ TIM5->IER |= (uint8_t)TIM5_IT; } else { /* Disable the Interrupt sources */ TIM5->IER &= (uint8_t)(~TIM5_IT); } } /** * @brief Enables or Disables the TIM5 Update event. * @param NewState new state of the TIM5 peripheral Preload register.This parameter can * be ENABLE or DISABLE. * @retval None */ void TIM5_UpdateDisableConfig(FunctionalState NewState) { /* Check the parameters */ assert_param(IS_FUNCTIONALSTATE_OK(NewState)); /* Set or Reset the UDIS Bit */ if (NewState != DISABLE) { TIM5->CR1 |= TIM5_CR1_UDIS ; } else { TIM5->CR1 &= (uint8_t)(~TIM5_CR1_UDIS) ; } } /** * @brief Selects the TIM5 Update Request Interrupt source. * @param TIM5_UpdateSource specifies the Update source. * This parameter can be one of the following values * - TIM5_UPDATESOURCE_REGULAR * - TIM5_UPDATESOURCE_GLOBAL * @retval None */ void TIM5_UpdateRequestConfig(TIM5_UpdateSource_TypeDef TIM5_UpdateSource) { /* Check the parameters */ assert_param(IS_TIM5_UPDATE_SOURCE_OK(TIM5_UpdateSource)); /* Set or Reset the URS Bit */ if (TIM5_UpdateSource != TIM5_UPDATESOURCE_GLOBAL) { TIM5->CR1 |= TIM5_CR1_URS ; } else { TIM5->CR1 &= (uint8_t)(~TIM5_CR1_URS) ; } } /** * @brief Selects the TIM5’s One Pulse Mode. * @param TIM5_OPMode specifies the OPM Mode to be used. * This parameter can be one of the following values * - TIM5_OPMODE_SINGLE * - TIM5_OPMODE_REPETITIVE * @retval None */ void TIM5_SelectOnePulseMode(TIM5_OPMode_TypeDef TIM5_OPMode) { /* Check the parameters */ assert_param(IS_TIM5_OPM_MODE_OK(TIM5_OPMode)); /* Set or Reset the OPM Bit */ if (TIM5_OPMode != TIM5_OPMODE_REPETITIVE) { TIM5->CR1 |= TIM5_CR1_OPM ; } else { TIM5->CR1 &= (uint8_t)(~TIM5_CR1_OPM) ; } } /** * @brief Configures the TIM5 Prescaler. * @param Prescaler specifies the Prescaler Register value * This parameter can be one of the following values * - TIM5_PRESCALER_1 * - TIM5_PRESCALER_2 * - TIM5_PRESCALER_4 * - TIM5_PRESCALER_8 * - TIM5_PRESCALER_16 * - TIM5_PRESCALER_32 * - TIM5_PRESCALER_64 * - TIM5_PRESCALER_128 * - TIM5_PRESCALER_256 * - TIM5_PRESCALER_512 * - TIM5_PRESCALER_1024 * - TIM5_PRESCALER_2048 * - TIM5_PRESCALER_4096 * - TIM5_PRESCALER_8192 * - TIM5_PRESCALER_16384 * - TIM5_PRESCALER_32768 * @param TIM5_PSCReloadMode specifies the TIM5 Prescaler Reload mode. * This parameter can be one of the following values * - TIM5_PSCRELOADMODE_IMMEDIATE: The Prescaler is loaded * immediately. * - TIM5_PSCRELOADMODE_UPDATE: The Prescaler is loaded at * the update event. * @retval None */ void TIM5_PrescalerConfig(TIM5_Prescaler_TypeDef Prescaler, TIM5_PSCReloadMode_TypeDef TIM5_PSCReloadMode) { /* Check the parameters */ assert_param(IS_TIM5_PRESCALER_RELOAD_OK(TIM5_PSCReloadMode)); assert_param(IS_TIM5_PRESCALER_OK(Prescaler)); /* Set the Prescaler value */ TIM5->PSCR = (uint8_t)Prescaler; /* Set or reset the UG Bit */ TIM5->EGR = (uint8_t)TIM5_PSCReloadMode ; } /** * @brief Forces the TIM5 Channel1 output waveform to active or inactive level. * @param TIM5_ForcedAction specifies the forced Action to be set to the output waveform. * This parameter can be one of the following values: * - TIM5_FORCEDACTION_ACTIVE: Force active level on OC1REF * - TIM5_FORCEDACTION_INACTIVE: Force inactive level on * OC1REF. * @retval None */ void TIM5_ForcedOC1Config(TIM5_ForcedAction_TypeDef TIM5_ForcedAction) { /* Check the parameters */ assert_param(IS_TIM5_FORCED_ACTION_OK(TIM5_ForcedAction)); /* Reset the OCM Bits */ /* Configure The Forced output Mode */ TIM5->CCMR1 = (uint8_t)((uint8_t)(TIM5->CCMR1 & (uint8_t)(~TIM5_CCMR_OCM)) | (uint8_t)TIM5_ForcedAction); } /** * @brief Forces the TIM5 Channel2 output waveform to active or inactive level. * @param TIM5_ForcedAction specifies the forced Action to be set to the output waveform. * This parameter can be one of the following values: * - TIM5_FORCEDACTION_ACTIVE: Force active level on OC2REF * - TIM5_FORCEDACTION_INACTIVE: Force inactive level on * OC2REF. * @retval None */ void TIM5_ForcedOC2Config(TIM5_ForcedAction_TypeDef TIM5_ForcedAction) { /* Check the parameters */ assert_param(IS_TIM5_FORCED_ACTION_OK(TIM5_ForcedAction)); /* Reset the OCM Bits */ /* Configure The Forced output Mode */ TIM5->CCMR2 = (uint8_t)((uint8_t)(TIM5->CCMR2 & (uint8_t)(~TIM5_CCMR_OCM)) | (uint8_t)TIM5_ForcedAction); } /** * @brief Forces the TIM5 Channel3 output waveform to active or inactive level. * @param TIM5_ForcedAction specifies the forced Action to be set to the output waveform. * This parameter can be one of the following values: * - TIM5_FORCEDACTION_ACTIVE: Force active level on OC3REF * - TIM5_FORCEDACTION_INACTIVE: Force inactive level on * OC3REF. * @retval None */ void TIM5_ForcedOC3Config(TIM5_ForcedAction_TypeDef TIM5_ForcedAction) { /* Check the parameters */ assert_param(IS_TIM5_FORCED_ACTION_OK(TIM5_ForcedAction)); /* Reset the OCM Bits */ /* Configure The Forced output Mode */ TIM5->CCMR3 = (uint8_t)((uint8_t)(TIM5->CCMR3 & (uint8_t)(~TIM5_CCMR_OCM)) | (uint8_t)TIM5_ForcedAction); } /** * @brief Enables or disables TIM5 peripheral Preload register on ARR. * @param NewState new state of the TIM5 peripheral Preload register. * This parameter can be ENABLE or DISABLE. * @retval None */ void TIM5_ARRPreloadConfig(FunctionalState NewState) { /* Check the parameters */ assert_param(IS_FUNCTIONALSTATE_OK(NewState)); /* Set or Reset the ARPE Bit */ if (NewState != DISABLE) { TIM5->CR1 |= TIM5_CR1_ARPE ; } else { TIM5->CR1 &= (uint8_t)(~TIM5_CR1_ARPE) ; } } /** * @brief Enables or disables the TIM5 peripheral Preload Register on CCR1. * @param NewState new state of the Capture Compare Preload register. * This parameter can be ENABLE or DISABLE. * @retval None */ void TIM5_OC1PreloadConfig(FunctionalState NewState) { /* Check the parameters */ assert_param(IS_FUNCTIONALSTATE_OK(NewState)); /* Set or Reset the OC1PE Bit */ if (NewState != DISABLE) { TIM5->CCMR1 |= TIM5_CCMR_OCxPE ; } else { TIM5->CCMR1 &= (uint8_t)(~TIM5_CCMR_OCxPE) ; } } /** * @brief Enables or disables the TIM5 peripheral Preload Register on CCR2. * @param NewState new state of the Capture Compare Preload register. * This parameter can be ENABLE or DISABLE. * @retval None */ void TIM5_OC2PreloadConfig(FunctionalState NewState) { /* Check the parameters */ assert_param(IS_FUNCTIONALSTATE_OK(NewState)); /* Set or Reset the OC2PE Bit */ if (NewState != DISABLE) { TIM5->CCMR2 |= TIM5_CCMR_OCxPE ; } else { TIM5->CCMR2 &= (uint8_t)(~TIM5_CCMR_OCxPE) ; } } /** * @brief Enables or disables the TIM5 peripheral Preload Register on CCR3. * @param NewState new state of the Capture Compare Preload register. * This parameter can be ENABLE or DISABLE. * @retval None */ void TIM5_OC3PreloadConfig(FunctionalState NewState) { /* Check the parameters */ assert_param(IS_FUNCTIONALSTATE_OK(NewState)); /* Set or Reset the OC3PE Bit */ if (NewState != DISABLE) { TIM5->CCMR3 |= TIM5_CCMR_OCxPE ; } else { TIM5->CCMR3 &= (uint8_t)(~TIM5_CCMR_OCxPE) ; } } /** * @brief Configures the TIM5 event to be generated by software. * @param TIM5_EventSource specifies the event source. * This parameter can be one of the following values: * - TIM5_EVENTSOURCE_UPDATE: TIM5 update Event source * - TIM5_EVENTSOURCE_CC1: TIM5 Capture Compare 1 Event source * - TIM5_EVENTSOURCE_CC2: TIM5 Capture Compare 2 Event source * - TIM5_EVENTSOURCE_CC3: TIM5 Capture Compare 3 Event source * @retval None */ void TIM5_GenerateEvent(TIM5_EventSource_TypeDef TIM5_EventSource) { /* Check the parameters */ assert_param(IS_TIM5_EVENT_SOURCE_OK(TIM5_EventSource)); /* Set the event sources */ TIM5->EGR = (uint8_t)TIM5_EventSource; } /** * @brief Configures the TIM5 Channel 1 polarity. * @param TIM5_OCPolarity specifies the OC1 Polarity. * This parameter can be one of the following values: * - TIM5_OCPOLARITY_LOW: Output Compare active low * - TIM5_OCPOLARITY_HIGH: Output Compare active high * @retval None */ void TIM5_OC1PolarityConfig(TIM5_OCPolarity_TypeDef TIM5_OCPolarity) { /* Check the parameters */ assert_param(IS_TIM5_OC_POLARITY_OK(TIM5_OCPolarity)); /* Set or Reset the CC1P Bit */ if (TIM5_OCPolarity != TIM5_OCPOLARITY_HIGH) { TIM5->CCER1 |= TIM5_CCER1_CC1P ; } else { TIM5->CCER1 &= (uint8_t)(~TIM5_CCER1_CC1P) ; } } /** * @brief Configures the TIM5 Channel 2 polarity. * @param TIM5_OCPolarity specifies the OC2 Polarity. * This parameter can be one of the following values: * - TIM5_OCPOLARITY_LOW: Output Compare active low * - TIM5_OCPOLARITY_HIGH: Output Compare active high * @retval None */ void TIM5_OC2PolarityConfig(TIM5_OCPolarity_TypeDef TIM5_OCPolarity) { /* Check the parameters */ assert_param(IS_TIM5_OC_POLARITY_OK(TIM5_OCPolarity)); /* Set or Reset the CC2P Bit */ if (TIM5_OCPolarity != TIM5_OCPOLARITY_HIGH) { TIM5->CCER1 |= TIM5_CCER1_CC2P ; } else { TIM5->CCER1 &= (uint8_t)(~TIM5_CCER1_CC2P) ; } } /** * @brief Configures the TIM5 Channel 3 polarity. * @param TIM5_OCPolarity specifies the OC3 Polarity. * This parameter can be one of the following values: * - TIM5_OCPOLARITY_LOW: Output Compare active low * - TIM5_OCPOLARITY_HIGH: Output Compare active high * @retval None */ void TIM5_OC3PolarityConfig(TIM5_OCPolarity_TypeDef TIM5_OCPolarity) { /* Check the parameters */ assert_param(IS_TIM5_OC_POLARITY_OK(TIM5_OCPolarity)); /* Set or Reset the CC3P Bit */ if (TIM5_OCPolarity != TIM5_OCPOLARITY_HIGH) { TIM5->CCER2 |= TIM5_CCER2_CC3P ; } else { TIM5->CCER2 &= (uint8_t)(~TIM5_CCER2_CC3P) ; } } /** * @brief Enables or disables the TIM5 Capture Compare Channel x. * @param TIM5_Channel specifies the TIM5 Channel. * This parameter can be one of the following values: * - TIM5_Channel1: TIM5 Channel1 * - TIM5_Channel2: TIM5 Channel2 * - TIM5_Channel3: TIM5 Channel3 * @param NewState specifies the TIM5 Channel CCxE bit new state. * This parameter can be: ENABLE or DISABLE. * @retval None */ void TIM5_CCxCmd(TIM5_Channel_TypeDef TIM5_Channel, FunctionalState NewState) { /* Check the parameters */ assert_param(IS_TIM5_CHANNEL_OK(TIM5_Channel)); assert_param(IS_FUNCTIONALSTATE_OK(NewState)); if (TIM5_Channel == TIM5_CHANNEL_1) { /* Set or Reset the CC1E Bit */ if (NewState != DISABLE) { TIM5->CCER1 |= TIM5_CCER1_CC1E ; } else { TIM5->CCER1 &= (uint8_t)(~TIM5_CCER1_CC1E) ; } } else if (TIM5_Channel == TIM5_CHANNEL_2) { /* Set or Reset the CC2E Bit */ if (NewState != DISABLE) { TIM5->CCER1 |= TIM5_CCER1_CC2E; } else { TIM5->CCER1 &= (uint8_t)(~TIM5_CCER1_CC2E) ; } } else { /* Set or Reset the CC3E Bit */ if (NewState != DISABLE) { TIM5->CCER2 |= TIM5_CCER2_CC3E; } else { TIM5->CCER2 &= (uint8_t)(~TIM5_CCER2_CC3E) ; } } } /** * @brief Selects the TIM5 Output Compare Mode. This function disables the * selected channel before changing the Output Compare Mode. User has to * enable this channel using TIM5_CCxCmd and TIM5_CCxNCmd functions. * @param TIM5_Channel specifies the TIM5 Channel. * This parameter can be one of the following values: * - TIM5_Channel1: TIM5 Channel1 * - TIM5_Channel2: TIM5 Channel2 * - TIM5_Channel3: TIM5 Channel3 * @param TIM5_OCMode specifies the TIM5 Output Compare Mode. * This parameter can be one of the following values: * - TIM5_OCMODE_TIMING * - TIM5_OCMODE_ACTIVE * - TIM5_OCMODE_TOGGLE * - TIM5_OCMODE_PWM1 * - TIM5_OCMODE_PWM2 * - TIM5_FORCEDACTION_ACTIVE * - TIM5_FORCEDACTION_INACTIVE * @retval None */ void TIM5_SelectOCxM(TIM5_Channel_TypeDef TIM5_Channel, TIM5_OCMode_TypeDef TIM5_OCMode) { /* Check the parameters */ assert_param(IS_TIM5_CHANNEL_OK(TIM5_Channel)); assert_param(IS_TIM5_OCM_OK(TIM5_OCMode)); if (TIM5_Channel == TIM5_CHANNEL_1) { /* Disable the Channel 1: Reset the CCE Bit */ TIM5->CCER1 &= (uint8_t)(~TIM5_CCER1_CC1E); /* Reset the Output Compare Bits Set the Output Compare Mode */ TIM5->CCMR1 = (uint8_t)((uint8_t)(TIM5->CCMR1 & (uint8_t)(~TIM5_CCMR_OCM)) | (uint8_t)TIM5_OCMode); } else if (TIM5_Channel == TIM5_CHANNEL_2) { /* Disable the Channel 2: Reset the CCE Bit */ TIM5->CCER1 &= (uint8_t)(~TIM5_CCER1_CC2E); /* Reset the Output Compare Bits ** Set the Output Compare Mode */ TIM5->CCMR2 = (uint8_t)((uint8_t)(TIM5->CCMR2 & (uint8_t)(~TIM5_CCMR_OCM)) | (uint8_t)TIM5_OCMode); } else { /* Disable the Channel 3: Reset the CCE Bit */ TIM5->CCER2 &= (uint8_t)(~TIM5_CCER2_CC3E); /* Reset the Output Compare Bits ** Set the Output Compare Mode */ TIM5->CCMR3 = (uint8_t)((uint8_t)(TIM5->CCMR3 & (uint8_t)(~TIM5_CCMR_OCM)) | (uint8_t)TIM5_OCMode); } } /** * @brief Sets the TIM5 Counter Register value. * @param Counter specifies the Counter register new value. * This parameter is between 0x0000 and 0xFFFF. * @retval None */ void TIM5_SetCounter(uint16_t Counter) { /* Set the Counter Register value */ TIM5->CNTRH = (uint8_t)(Counter >> 8); TIM5->CNTRL = (uint8_t)(Counter); } /** * @brief Sets the TIM5 Autoreload Register value. * @param Autoreload specifies the Autoreload register new value. * This parameter is between 0x0000 and 0xFFFF. * @retval None */ void TIM5_SetAutoreload(uint16_t Autoreload) { /* Set the Autoreload Register value */ TIM5->ARRH = (uint8_t)(Autoreload >> 8); TIM5->ARRL = (uint8_t)(Autoreload); } /** * @brief Sets the TIM5 Capture Compare1 Register value. * @param Compare1 specifies the Capture Compare1 register new value. * This parameter is between 0x0000 and 0xFFFF. * @retval None */ void TIM5_SetCompare1(uint16_t Compare1) { /* Set the Capture Compare1 Register value */ TIM5->CCR1H = (uint8_t)(Compare1 >> 8); TIM5->CCR1L = (uint8_t)(Compare1); } /** * @brief Sets the TIM5 Capture Compare2 Register value. * @param Compare2 specifies the Capture Compare2 register new value. * This parameter is between 0x0000 and 0xFFFF. * @retval None */ void TIM5_SetCompare2(uint16_t Compare2) { /* Set the Capture Compare2 Register value */ TIM5->CCR2H = (uint8_t)(Compare2 >> 8); TIM5->CCR2L = (uint8_t)(Compare2); } /** * @brief Sets the TIM5 Capture Compare3 Register value. * @param Compare3 specifies the Capture Compare3 register new value. * This parameter is between 0x0000 and 0xFFFF. * @retval None */ void TIM5_SetCompare3(uint16_t Compare3) { /* Set the Capture Compare3 Register value */ TIM5->CCR3H = (uint8_t)(Compare3 >> 8); TIM5->CCR3L = (uint8_t)(Compare3); } /** * @brief Sets the TIM5 Input Capture 1 prescaler. * @param TIM5_IC1Prescaler specifies the Input Capture prescaler new value * This parameter can be one of the following values: * - TIM5_ICPSC_DIV1: no prescaler * - TIM5_ICPSC_DIV2: capture is done once every 2 events * - TIM5_ICPSC_DIV4: capture is done once every 4 events * - TIM5_ICPSC_DIV8: capture is done once every 8 events * @retval None */ void TIM5_SetIC1Prescaler(TIM5_ICPSC_TypeDef TIM5_IC1Prescaler) { /* Check the parameters */ assert_param(IS_TIM5_IC_PRESCALER_OK(TIM5_IC1Prescaler)); /* Reset the IC1PSC Bits */ /* Set the IC1PSC value */ TIM5->CCMR1 = (uint8_t)((uint8_t)(TIM5->CCMR1 & (uint8_t)(~TIM5_CCMR_ICxPSC))| (uint8_t)TIM5_IC1Prescaler); } /** * @brief Sets the TIM5 Input Capture 2 prescaler. * @param TIM5_IC2Prescaler specifies the Input Capture prescaler new value * This parameter can be one of the following values: * - TIM5_ICPSC_DIV1: no prescaler * - TIM5_ICPSC_DIV2: capture is done once every 2 events * - TIM5_ICPSC_DIV4: capture is done once every 4 events * - TIM5_ICPSC_DIV8: capture is done once every 8 events * @retval None */ void TIM5_SetIC2Prescaler(TIM5_ICPSC_TypeDef TIM5_IC2Prescaler) { /* Check the parameters */ assert_param(IS_TIM5_IC_PRESCALER_OK(TIM5_IC2Prescaler)); /* Reset the IC1PSC Bits */ /* Set the IC1PSC value */ TIM5->CCMR2 = (uint8_t)((uint8_t)(TIM5->CCMR2 & (uint8_t)(~TIM5_CCMR_ICxPSC)) | (uint8_t)TIM5_IC2Prescaler); } /** * @brief Sets the TIM5 Input Capture 3 prescaler. * @param TIM5_IC3Prescaler specifies the Input Capture prescaler new value * This parameter can be one of the following values: * - TIM5_ICPSC_DIV1: no prescaler * - TIM5_ICPSC_DIV2: capture is done once every 2 events * - TIM5_ICPSC_DIV4: capture is done once every 4 events * - TIM5_ICPSC_DIV8: capture is done once every 8 events * @retval None */ void TIM5_SetIC3Prescaler(TIM5_ICPSC_TypeDef TIM5_IC3Prescaler) { /* Check the parameters */ assert_param(IS_TIM5_IC_PRESCALER_OK(TIM5_IC3Prescaler)); /* Reset the IC1PSC Bits */ /* Set the IC1PSC value */ TIM5->CCMR3 = (uint8_t)((uint8_t)(TIM5->CCMR3 & (uint8_t)(~TIM5_CCMR_ICxPSC)) | (uint8_t)TIM5_IC3Prescaler); } /** * @brief Gets the TIM5 Input Capture 1 value. * @param None * @retval Capture Compare 1 Register value. */ uint16_t TIM5_GetCapture1(void) { uint16_t temp = 0; temp = ((uint16_t)TIM5->CCR1H << 8); /* Get the Capture 1 Register value */ return (uint16_t)(temp | (uint16_t)(TIM5->CCR1L)); } /** * @brief Gets the TIM5 Input Capture 2 value. * @param None * @retval Capture Compare 2 Register value. */ uint16_t TIM5_GetCapture2(void) { uint16_t temp = 0; temp = ((uint16_t)TIM5->CCR2H << 8); /* Get the Capture 2 Register value */ return (uint16_t)(temp | (uint16_t)(TIM5->CCR2L)); } /** * @brief Gets the TIM5 Input Capture 3 value. * @param None * @retval Capture Compare 3 Register value. */ uint16_t TIM5_GetCapture3(void) { uint16_t temp = 0; temp = ((uint16_t)TIM5->CCR3H << 8); /* Get the Capture 1 Register value */ return (uint16_t)(temp | (uint16_t)(TIM5->CCR3L)); } /** * @brief Gets the TIM5 Counter value. * @param None * @retval Counter Register value. */ uint16_t TIM5_GetCounter(void) { uint16_t tmpcntr = 0; tmpcntr = ((uint16_t)TIM5->CNTRH << 8); /* Get the Counter Register value */ return (uint16_t)(tmpcntr | (uint16_t)(TIM5->CNTRL)); } /** * @brief Gets the TIM5 Prescaler value. * @param None * @retval Prescaler Register configuration value @ref TIM5_Prescaler_TypeDef . */ TIM5_Prescaler_TypeDef TIM5_GetPrescaler(void) { /* Get the Prescaler Register value */ return (TIM5_Prescaler_TypeDef)(TIM5->PSCR); } /** * @brief Checks whether the specified TIM5 flag is set or not. * @param TIM5_FLAG specifies the flag to check. * This parameter can be one of the following values: * - TIM5_FLAG_UPDATE: TIM5 update Flag * - TIM5_FLAG_CC1: TIM5 Capture Compare 1 Flag * - TIM5_FLAG_CC2: TIM5 Capture Compare 2 Flag * - TIM5_FLAG_CC3: TIM5 Capture Compare 3 Flag * - TIM5_FLAG_CC1OF: TIM5 Capture Compare 1 overcapture Flag * - TIM5_FLAG_CC2OF: TIM5 Capture Compare 2 overcapture Flag * - TIM5_FLAG_CC3OF: TIM5 Capture Compare 3 overcapture Flag * @retval FlagStatus The new state of TIM5_FLAG (SET or RESET). */ FlagStatus TIM5_GetFlagStatus(TIM5_FLAG_TypeDef TIM5_FLAG) { FlagStatus bitstatus = RESET; uint8_t tim5_flag_l, tim5_flag_h; /* Check the parameters */ assert_param(IS_TIM5_GET_FLAG_OK(TIM5_FLAG)); tim5_flag_l= (uint8_t)(TIM5->SR1 & (uint8_t)TIM5_FLAG); tim5_flag_h= (uint8_t)((uint16_t)TIM5_FLAG >> 8); if (((tim5_flag_l)|(uint8_t)(TIM5->SR2 & tim5_flag_h)) != RESET ) { bitstatus = SET; } else { bitstatus = RESET; } return (FlagStatus)bitstatus; } /** * @brief Clears the TIM5’s pending flags. * @param TIM5_FLAG specifies the flag to clear. * This parameter can be one of the following values: * - TIM5_FLAG_UPDATE: TIM5 update Flag * - TIM5_FLAG_CC1: TIM5 Capture Compare 1 Flag * - TIM5_FLAG_CC2: TIM5 Capture Compare 2 Flag * - TIM5_FLAG_CC3: TIM5 Capture Compare 3 Flag * - TIM5_FLAG_CC1OF: TIM5 Capture Compare 1 overcapture Flag * - TIM5_FLAG_CC2OF: TIM5 Capture Compare 2 overcapture Flag * - TIM5_FLAG_CC3OF: TIM5 Capture Compare 3 overcapture Flag * @retval None. */ void TIM5_ClearFlag(TIM5_FLAG_TypeDef TIM5_FLAG) { /* Check the parameters */ assert_param(IS_TIM5_CLEAR_FLAG_OK(TIM5_FLAG)); /* Clear the flags (rc_w0) clear this bit by writing 0. Writing ‘1’ has no effect*/ TIM5->SR1 = (uint8_t)(~((uint8_t)(TIM5_FLAG))); TIM5->SR2 &= (uint8_t)(~((uint8_t)((uint16_t)TIM5_FLAG >> 8))); } /** * @brief Checks whether the TIM5 interrupt has occurred or not. * @param TIM5_IT specifies the TIM5 interrupt source to check. * This parameter can be one of the following values: * - TIM5_IT_UPDATE: TIM5 update Interrupt source * - TIM5_IT_CC1: TIM5 Capture Compare 1 Interrupt source * - TIM5_IT_CC2: TIM5 Capture Compare 2 Interrupt source * - TIM5_IT_CC3: TIM5 Capture Compare 3 Interrupt source * @retval ITStatus The new state of the TIM5_IT(SET or RESET). */ ITStatus TIM5_GetITStatus(TIM5_IT_TypeDef TIM5_IT) { ITStatus bitstatus = RESET; uint8_t TIM5_itStatus = 0, TIM5_itEnable = 0; /* Check the parameters */ assert_param(IS_TIM5_GET_IT_OK(TIM5_IT)); TIM5_itStatus = (uint8_t)(TIM5->SR1 & TIM5_IT); TIM5_itEnable = (uint8_t)(TIM5->IER & TIM5_IT); if ((TIM5_itStatus != (uint8_t)RESET ) && (TIM5_itEnable != (uint8_t)RESET )) { bitstatus = SET; } else { bitstatus = RESET; } return (ITStatus)(bitstatus); } /** * @brief Clears the TIM5's interrupt pending bits. * @param TIM5_IT specifies the pending bit to clear. * This parameter can be one of the following values: * - TIM5_IT_UPDATE: TIM5 update Interrupt source * - TIM5_IT_CC1: TIM5 Capture Compare 1 Interrupt source * - TIM5_IT_CC2: TIM5 Capture Compare 2 Interrupt source * - TIM5_IT_CC3: TIM5 Capture Compare 3 Interrupt source * @retval None. */ void TIM5_ClearITPendingBit(TIM5_IT_TypeDef TIM5_IT) { /* Check the parameters */ assert_param(IS_TIM5_IT_OK(TIM5_IT)); /* Clear the IT pending Bit */ TIM5->SR1 = (uint8_t)(~TIM5_IT); } /** * @brief Configure the TI1 as Input. * @param TIM5_ICPolarity The Input Polarity. * This parameter can be one of the following values: * - TIM5_ICPOLARITY_FALLING * - TIM5_ICPOLARITY_RISING * @param TIM5_ICSelection specifies the input to be used. * This parameter can be one of the following values: * - TIM5_ICSELECTION_DIRECTTI: TIM5 Input 1 is selected to * be connected to IC1. * - TIM5_ICSELECTION_INDIRECTTI: TIM5 Input 1 is selected to * be connected to IC2. * @param TIM5_ICFilter Specifies the Input Capture Filter. * This parameter must be a value between 0x00 and 0x0F. * @retval None */ static void TI1_Config(uint8_t TIM5_ICPolarity, uint8_t TIM5_ICSelection, uint8_t TIM5_ICFilter) { /* Disable the Channel 1: Reset the CCE Bit */ TIM5->CCER1 &= (uint8_t)(~TIM5_CCER1_CC1E); /* Select the Input and set the filter */ TIM5->CCMR1 = (uint8_t)((uint8_t)(TIM5->CCMR1 & (uint8_t)(~( TIM5_CCMR_CCxS | TIM5_CCMR_ICxF ))) | (uint8_t)(( (TIM5_ICSelection)) | ((uint8_t)( TIM5_ICFilter << 4)))); /* Select the Polarity */ if (TIM5_ICPolarity != TIM5_ICPOLARITY_RISING) { TIM5->CCER1 |= TIM5_CCER1_CC1P ; } else { TIM5->CCER1 &= (uint8_t)(~TIM5_CCER1_CC1P) ; } /* Set the CCE Bit */ TIM5->CCER1 |= TIM5_CCER1_CC1E; } /** * @brief Configure the TI2 as Input. * @param TIM5_ICPolarity The Input Polarity. * This parameter can be one of the following values: * - TIM5_ICPOLARITY_FALLING * - TIM5_ICPOLARITY_RISING * @param TIM5_ICSelection specifies the input to be used. * This parameter can be one of the following values: * - TIM5_ICSELECTION_DIRECTTI: TIM5 Input 2 is selected to * be connected to IC2. * - TIM5_ICSELECTION_INDIRECTTI: TIM5 Input 2 is selected to * be connected to IC1. * @param TIM5_ICFilter Specifies the Input Capture Filter. * This parameter must be a value between 0x00 and 0x0F. * @retval None */ static void TI2_Config(uint8_t TIM5_ICPolarity, uint8_t TIM5_ICSelection, uint8_t TIM5_ICFilter) { /* Disable the Channel 2: Reset the CCE Bit */ TIM5->CCER1 &= (uint8_t)(~TIM5_CCER1_CC2E); /* Select the Input and set the filter */ TIM5->CCMR2 = (uint8_t)((uint8_t)(TIM5->CCMR2 & (uint8_t)(~( TIM5_CCMR_CCxS | TIM5_CCMR_ICxF))) | (uint8_t)(( (TIM5_ICSelection)) | ((uint8_t)( TIM5_ICFilter << 4)))); /* Select the Polarity */ if (TIM5_ICPolarity != TIM5_ICPOLARITY_RISING) { TIM5->CCER1 |= TIM5_CCER1_CC2P ; } else { TIM5->CCER1 &= (uint8_t)(~TIM5_CCER1_CC2P) ; } /* Set the CCE Bit */ TIM5->CCER1 |= TIM5_CCER1_CC2E; } /** * @brief Configure the TI3 as Input. * @param TIM5_ICPolarity The Input Polarity. * This parameter can be one of the following values: * - TIM5_ICPOLARITY_FALLING * - TIM5_ICPOLARITY_RISING * @param TIM5_ICSelection specifies the input to be used. * This parameter can be one of the following values: * - TIM5_ICSELECTION_DIRECTTI: TIM5 Input 3 is selected to * be connected to IC3. * @param TIM5_ICFilter Specifies the Input Capture Filter. * This parameter must be a value between 0x00 and 0x0F. * @retval None */ static void TI3_Config(uint8_t TIM5_ICPolarity, uint8_t TIM5_ICSelection, uint8_t TIM5_ICFilter) { /* Disable the Channel 3: Reset the CCE Bit */ TIM5->CCER2 &= (uint8_t)(~TIM5_CCER2_CC3E); /* Select the Input and set the filter */ TIM5->CCMR3 = (uint8_t)((uint8_t)(TIM5->CCMR3 & (uint8_t)(~( TIM5_CCMR_CCxS | TIM5_CCMR_ICxF))) | (uint8_t)(( (TIM5_ICSelection)) | ((uint8_t)( TIM5_ICFilter << 4)))); /* Select the Polarity */ if (TIM5_ICPolarity != TIM5_ICPOLARITY_RISING) { TIM5->CCER2 |= TIM5_CCER2_CC3P ; } else { TIM5->CCER2 &= (uint8_t)(~TIM5_CCER2_CC3P) ; } /* Set the CCE Bit */ TIM5->CCER2 |= TIM5_CCER2_CC3E; } /** * @brief Enables the TIM5 internal Clock. * @par Parameters: * None * @retval None */ void TIM5_InternalClockConfig(void) { /* Disable slave mode to clock the prescaler directly with the internal clock */ TIM5->SMCR &= (uint8_t)(~TIM5_SMCR_SMS); } /** * @brief Selects the TIM5 Trigger Output Mode. * @param TIM5_TRGOSource : Specifies the Trigger Output source. * This parameter can be one of the @ref TIM5_TRGOSource_TypeDef enumeration. * @retval None */ void TIM5_SelectOutputTrigger(TIM5_TRGOSource_TypeDef TIM5_TRGOSource) { uint8_t tmpcr2 = 0; /* Check the parameters */ assert_param(IS_TIM5_TRGO_SOURCE_OK(TIM5_TRGOSource)); tmpcr2 = TIM5->CR2; /* Reset the MMS Bits */ tmpcr2 &= (uint8_t)(~TIM5_CR2_MMS); /* Select the TRGO source */ tmpcr2 |= (uint8_t)TIM5_TRGOSource; TIM5->CR2 = tmpcr2; } /** * @brief Selects the TIM5 Slave Mode. * @param TIM5_SlaveMode : Specifies the TIM5 Slave Mode. * This parameter can be one of the @ref TIM5_SlaveMode_TypeDef enumeration. * @retval None */ void TIM5_SelectSlaveMode(TIM5_SlaveMode_TypeDef TIM5_SlaveMode) { uint8_t tmpsmcr = 0; /* Check the parameters */ assert_param(IS_TIM5_SLAVE_MODE_OK(TIM5_SlaveMode)); tmpsmcr = TIM5->SMCR; /* Reset the SMS Bits */ tmpsmcr &= (uint8_t)(~TIM5_SMCR_SMS); /* Select the Slave Mode */ tmpsmcr |= (uint8_t)TIM5_SlaveMode; TIM5->SMCR = tmpsmcr; } /** * @brief Selects the TIM5 Input Trigger source. * @param TIM5_InputTriggerSource : Specifies Input Trigger source. * This parameter can be one of the @ref TIM5_TS_TypeDef enumeration. * @retval None */ void TIM5_SelectInputTrigger(TIM5_TS_TypeDef TIM5_InputTriggerSource) { uint8_t tmpsmcr = 0; /* Check the parameters */ assert_param(IS_TIM5_TRIGGER_SELECTION_OK(TIM5_InputTriggerSource)); tmpsmcr = TIM5->SMCR; /* Select the Trigger Source */ tmpsmcr &= (uint8_t)(~TIM5_SMCR_TS); tmpsmcr |= (uint8_t)TIM5_InputTriggerSource; TIM5->SMCR = (uint8_t)tmpsmcr; } /** * @brief Configures the TIM5 Encoder Interface. * @param TIM5_EncoderMode : Specifies the TIM5 Encoder Mode. * This parameter can be one of the @ref TIM5_EncoderMode_TypeDef enumeration. * @param TIM5_IC1Polarity : Specifies the IC1 Polarity. * This parameter can be one of the @ref TIM5_ICPolarity_TypeDef enumeration. * @param TIM5_IC2Polarity : Specifies the IC2 Polarity. * This parameter can be one of the @ref TIM5_ICPolarity_TypeDef enumeration. * @retval None */ void TIM5_EncoderInterfaceConfig(TIM5_EncoderMode_TypeDef TIM5_EncoderMode, TIM5_ICPolarity_TypeDef TIM5_IC1Polarity, TIM5_ICPolarity_TypeDef TIM5_IC2Polarity) { uint8_t tmpsmcr = 0; uint8_t tmpccmr1 = 0; uint8_t tmpccmr2 = 0; /* Check the parameters */ assert_param(IS_TIM5_ENCODER_MODE_OK(TIM5_EncoderMode)); assert_param(IS_TIM5_IC_POLARITY_OK(TIM5_IC1Polarity)); assert_param(IS_TIM5_IC_POLARITY_OK(TIM5_IC2Polarity)); tmpsmcr = TIM5->SMCR; tmpccmr1 = TIM5->CCMR1; tmpccmr2 = TIM5->CCMR2; /* Set the encoder Mode */ tmpsmcr &= (uint8_t)(TIM5_SMCR_MSM | TIM5_SMCR_TS) ; tmpsmcr |= (uint8_t)TIM5_EncoderMode; /* Select the Capture Compare 1 and the Capture Compare 2 as input */ tmpccmr1 &= (uint8_t)(~TIM5_CCMR_CCxS); tmpccmr2 &= (uint8_t)(~TIM5_CCMR_CCxS); tmpccmr1 |= TIM5_CCMR_TIxDirect_Set; tmpccmr2 |= TIM5_CCMR_TIxDirect_Set; /* Set the TI1 and the TI2 Polarities */ if (TIM5_IC1Polarity == TIM5_ICPOLARITY_FALLING) { TIM5->CCER1 |= TIM5_CCER1_CC1P ; } else { TIM5->CCER1 &= (uint8_t)(~TIM5_CCER1_CC1P) ; } if (TIM5_IC2Polarity == TIM5_ICPOLARITY_FALLING) { TIM5->CCER1 |= TIM5_CCER1_CC2P ; } else { TIM5->CCER1 &= (uint8_t)(~TIM5_CCER1_CC2P) ; } TIM5->SMCR = tmpsmcr; TIM5->CCMR1 = tmpccmr1; TIM5->CCMR2 = tmpccmr2; } /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
SeanGau/Arduino_Core_STM8
cores/arduino/stm8/analog.c
<reponame>SeanGau/Arduino_Core_STM8<filename>cores/arduino/stm8/analog.c /** ****************************************************************************** * @file analog.c * @author WI6LABS * @version V1.0.0 * @date 16-September-2016 * @brief provide analog services (ADC + PWM) * ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2016 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ #include "analog.h" #include "stm8_def.h" #include "timer.h" #include "PinAF_STM8Lxx.h" #ifdef __cplusplus extern "C" { #endif static PinName g_current_pin = NC; static uint16_t get_adc_channel(PinName pin) { uint16_t function = pinmap_function(pin, PinMap_ADC); uint16_t channel = 0; #if defined(STM8Sxx) #if defined(ADC2) switch (STM_PIN_CHANNEL(function)) { case 1: channel = ADC2_CHANNEL_1; break; case 2: channel = ADC2_CHANNEL_2; break; case 3: channel = ADC2_CHANNEL_3; break; case 4: channel = ADC2_CHANNEL_4; break; case 5: channel = ADC2_CHANNEL_5; break; case 6: channel = ADC2_CHANNEL_6; break; case 7: channel = ADC2_CHANNEL_7; break; case 8: channel = ADC2_CHANNEL_8; break; case 9: channel = ADC2_CHANNEL_9; break; case 12: channel = ADC2_CHANNEL_12; break; case 13: channel = ADC2_CHANNEL_13; break; case 14: channel = ADC2_CHANNEL_14; break; case 15: channel = ADC2_CHANNEL_15; break; default: channel = 0; break; } #elif defined(ADC1) switch (STM_PIN_CHANNEL(function)) { case 1: channel = ADC1_CHANNEL_1; break; case 2: channel = ADC1_CHANNEL_2; break; case 3: channel = ADC1_CHANNEL_3; break; case 4: channel = ADC1_CHANNEL_4; break; case 5: channel = ADC1_CHANNEL_5; break; case 6: channel = ADC1_CHANNEL_6; break; case 7: channel = ADC1_CHANNEL_7; break; case 8: channel = ADC1_CHANNEL_8; break; case 9: channel = ADC1_CHANNEL_9; break; case 12: channel = ADC1_CHANNEL_12; break; default: channel = 0; break; } #endif #elif defined(STM8Lxx) switch (STM_PIN_CHANNEL(function)) { case 0: channel = ADC_Channel_0; break; case 1: channel = ADC_Channel_1; break; case 2: channel = ADC_Channel_2; break; case 3: channel = ADC_Channel_3; break; case 4: channel = ADC_Channel_4; break; case 5: channel = ADC_Channel_5; break; case 6: channel = ADC_Channel_6; break; case 7: channel = ADC_Channel_7; break; case 8: channel = ADC_Channel_8; break; case 9: channel = ADC_Channel_9; break; case 10: channel = ADC_Channel_10; break; case 11: channel = ADC_Channel_11; break; case 12: channel = ADC_Channel_12; break; case 13: channel = ADC_Channel_13; break; case 14: channel = ADC_Channel_14; break; case 15: channel = ADC_Channel_15; break; case 16: channel = ADC_Channel_16; break; case 17: channel = ADC_Channel_17; break; case 18: channel = ADC_Channel_18; break; case 19: channel = ADC_Channel_19; break; case 20: channel = ADC_Channel_20; break; case 21: channel = ADC_Channel_21; break; case 22: channel = ADC_Channel_22; break; case 23: channel = ADC_Channel_23; break; case 24: channel = ADC_Channel_24; break; case 25: channel = ADC_Channel_25; break; case 26: channel = ADC_Channel_26; break; case 27: channel = ADC_Channel_27; break; default: channel = 0; break; } #endif return channel; } static uint8_t get_pwm_channel(PinName pin) { uint16_t function = pinmap_function(pin, PinMap_PWM); uint8_t channel = 0; switch (STM_PIN_CHANNEL(function)) { case 1: channel = 0x01; break; case 2: channel = 0x02; break; case 3: channel = 0x03; break; case 4: channel = 0x04; break; default: break; } return channel; } uint16_t adc_read_value(PinName pin) { uint16_t channel = get_adc_channel(pin); void *peripheral = pinmap_peripheral(pin, PinMap_ADC); __IO uint16_t uhADCxConvertedValue = 0; #if defined(STM8Sxx) #if defined(ADC2) ADC2_DeInit(); ADC2_Init(ADC2_CONVERSIONMODE_SINGLE, (uint8_t)channel, ADC2_PRESSEL_FCPU_D2, ADC2_EXTTRIG_TIM, DISABLE, ADC2_ALIGN_RIGHT, ADC2_SCHMITTTRIG_CHANNEL12, DISABLE); ADC2_StartConversion(); while(ADC2_GetFlagStatus() == RESET); ADC2_ClearFlag(); uhADCxConvertedValue = ADC2_GetConversionValue(); ADC2_Cmd(DISABLE); return uhADCxConvertedValue; #endif #if defined(ADC1) ADC1_DeInit(); ADC1_Init(ADC1_CONVERSIONMODE_SINGLE, (uint8_t)channel, ADC1_PRESSEL_FCPU_D2, ADC1_EXTTRIG_TIM, DISABLE, ADC1_ALIGN_RIGHT, ADC1_SCHMITTTRIG_CHANNEL12, DISABLE); ADC1_StartConversion(); while(ADC1_GetFlagStatus(ADC1_FLAG_EOC) == RESET); ADC1_ClearFlag(ADC1_FLAG_EOC); uhADCxConvertedValue = ADC1_GetConversionValue(); ADC1_Cmd(DISABLE); return uhADCxConvertedValue; #endif #endif #if defined(STM8Lxx) CLK_PeripheralClockConfig(CLK_Peripheral_ADC1, ENABLE); ADC_DeInit(ADC1); ADC_Init(ADC1, ADC_ConversionMode_Single, ADC_Resolution_10Bit, ADC_Prescaler_1); ADC_SamplingTimeConfig(ADC1, ADC_Group_SlowChannels, ADC_SamplingTime_384Cycles); ADC_Cmd(ADC1, ENABLE); ADC_ChannelCmd(ADC1, channel, ENABLE); ADC_SoftwareStartConv(ADC1); while(ADC_GetFlagStatus(ADC1,ADC_FLAG_EOC) == RESET); ADC_ClearFlag(ADC1, ADC_FLAG_EOC); uhADCxConvertedValue = ADC_GetConversionValue(ADC1); return uhADCxConvertedValue; #endif } void pwm_start(PinName pin, uint32_t clock_freq, uint32_t period, uint32_t value, uint8_t do_init) { void *peripheral = pinmap_peripheral(pin, PinMap_PWM); uint16_t function = pinmap_function(pin, PinMap_PWM); uint8_t id = get_pwm_channel(pin); #if defined(STM8Sxx) if (peripheral == TIM1) { TIM1_TimeBaseInit((uint16_t)(CLK_GetClockFreq() / clock_freq) - 1, TIM1_COUNTERMODE_UP, period-1, 0); switch (id) { case 1: TIM1_OC1Init(TIM1_OCMODE_PWM2, TIM1_OUTPUTSTATE_ENABLE, TIM1_OUTPUTNSTATE_ENABLE, value, TIM1_OCPOLARITY_LOW, TIM1_OCNPOLARITY_HIGH, TIM1_OCIDLESTATE_SET, TIM1_OCNIDLESTATE_RESET); break; case 2: TIM1_OC2Init(TIM1_OCMODE_PWM2, TIM1_OUTPUTSTATE_ENABLE, TIM1_OUTPUTNSTATE_ENABLE, value, TIM1_OCPOLARITY_LOW, TIM1_OCNPOLARITY_HIGH, TIM1_OCIDLESTATE_SET, TIM1_OCNIDLESTATE_RESET); break; case 3: TIM1_OC3Init(TIM1_OCMODE_PWM2, TIM1_OUTPUTSTATE_ENABLE, TIM1_OUTPUTNSTATE_ENABLE, value, TIM1_OCPOLARITY_LOW, TIM1_OCNPOLARITY_HIGH, TIM1_OCIDLESTATE_SET, TIM1_OCNIDLESTATE_RESET); break; case 4: TIM1_OC4Init(TIM1_OCMODE_PWM2, TIM1_OUTPUTSTATE_ENABLE, value, TIM1_OCPOLARITY_LOW, TIM1_OCIDLESTATE_SET); break; default: return; } TIM1_Cmd(ENABLE); TIM1_CtrlPWMOutputs(ENABLE); } #ifdef TIM2 else if (peripheral == TIM2) { TIM2_TimeBaseInit(TIM2_PRESCALER_64, period-1); switch (id) { case 1: TIM2_OC1Init(TIM2_OCMODE_PWM1, TIM2_OUTPUTSTATE_ENABLE, value, TIM2_OCPOLARITY_HIGH); break; case 2: TIM2_OC2Init(TIM2_OCMODE_PWM1, TIM2_OUTPUTSTATE_ENABLE, value, TIM2_OCPOLARITY_HIGH); break; case 3: TIM2_OC3Init(TIM2_OCMODE_PWM1, TIM2_OUTPUTSTATE_ENABLE, value, TIM2_OCPOLARITY_HIGH); break; default: return; } TIM2_ARRPreloadConfig(ENABLE); TIM2_Cmd(ENABLE); } #endif #ifdef TIM3 else if (peripheral == TIM3) { TIM3_TimeBaseInit(TIM3_PRESCALER_64, period-1); switch (id) { case 1: TIM3_OC1Init(TIM3_OCMODE_PWM1, TIM3_OUTPUTSTATE_ENABLE, value, TIM3_OCPOLARITY_HIGH); break; case 2: TIM3_OC2Init(TIM3_OCMODE_PWM1, TIM3_OUTPUTSTATE_ENABLE, value, TIM2_OCPOLARITY_HIGH); break; default: return; } TIM3_ARRPreloadConfig(ENABLE); TIM3_Cmd(ENABLE); } #endif #ifdef TIM5 else if (peripheral == TIM5) { TIM5_TimeBaseInit(TIM5_PRESCALER_64, period-1); switch (id) { case 1: TIM5_OC1Init(TIM5_OCMODE_PWM1, TIM5_OUTPUTSTATE_ENABLE, value, TIM5_OCPOLARITY_HIGH); break; case 2: TIM5_OC2Init(TIM5_OCMODE_PWM1, TIM5_OUTPUTSTATE_ENABLE, value, TIM5_OCPOLARITY_HIGH); break; case 3: TIM5_OC3Init(TIM5_OCMODE_PWM1, TIM5_OUTPUTSTATE_ENABLE, value, TIM5_OCPOLARITY_HIGH); break; default: return; } TIM5_ARRPreloadConfig(ENABLE); TIM5_Cmd(ENABLE); } #endif else return; #elif defined(STM8Lxx) if (peripheral == TIM1) { CLK_PeripheralClockConfig(CLK_Peripheral_TIM1, ENABLE); if (do_init == 1) { TIM1_TimeBaseInit((uint16_t)(CLK_GetClockFreq() / clock_freq) - 1, TIM1_CounterMode_Up, period-1, 0); } switch (id) { case 1: TIM1_OC1Init(TIM1_OCMode_PWM2, TIM1_OutputState_Enable, TIM1_OutputNState_Enable, value, TIM1_OCPolarity_Low, TIM1_OCNPolarity_High, TIM1_OCIdleState_Set, TIM1_OCNIdleState_Reset); break; case 2: TIM1_OC2Init(TIM1_OCMode_PWM2, TIM1_OutputState_Enable, TIM1_OutputNState_Enable, value, TIM1_OCPolarity_Low, TIM1_OCNPolarity_High, TIM1_OCIdleState_Set, TIM1_OCNIdleState_Reset); break; case 3: TIM1_OC3Init(TIM1_OCMode_PWM2, TIM1_OutputState_Enable, TIM1_OutputNState_Enable, value, TIM1_OCPolarity_Low, TIM1_OCNPolarity_High, TIM1_OCIdleState_Set, TIM1_OCNIdleState_Reset); break; default: return; } TIM1_Cmd(ENABLE); TIM1_CtrlPWMOutputs(ENABLE); } else if (peripheral == TIM2) { CLK_PeripheralClockConfig(CLK_Peripheral_TIM2, ENABLE); TIM2_TimeBaseInit(TIM2_Prescaler_64, TIM2_CounterMode_Up, period-1); pin_Set8LAFPin(STM_PIN_AFNUM(function)); switch (id) { case 1: TIM2_OC1Init(TIM2_OCMode_PWM1, TIM2_OutputState_Enable, value, TIM2_OCPolarity_High, TIM2_OCIdleState_Set); break; case 2: TIM2_OC2Init(TIM2_OCMode_PWM1, TIM2_OutputState_Enable, value, TIM2_OCPolarity_High, TIM2_OCIdleState_Set); break; default: return; } TIM2_CtrlPWMOutputs(ENABLE); TIM2_Cmd(ENABLE); } else if (peripheral == TIM3) { CLK_PeripheralClockConfig(CLK_Peripheral_TIM3, ENABLE); TIM3_TimeBaseInit(TIM3_Prescaler_64, TIM3_CounterMode_Up, period-1); pin_Set8LAFPin(STM_PIN_AFNUM(function)); switch (id) { case 1: TIM3_OC1Init(TIM3_OCMode_PWM1, TIM3_OutputState_Enable, value, TIM3_OCPolarity_High, TIM3_OCIdleState_Set); break; case 2: TIM3_OC2Init(TIM3_OCMode_PWM1, TIM3_OutputState_Enable, value, TIM3_OCPolarity_High, TIM3_OCIdleState_Set); break; default: return; } TIM3_CtrlPWMOutputs(ENABLE); TIM3_Cmd(ENABLE); } else if (peripheral == TIM5) { CLK_PeripheralClockConfig(CLK_Peripheral_TIM5, ENABLE); TIM5_TimeBaseInit(TIM5_Prescaler_64, TIM5_CounterMode_Up, period-1); switch (id) { case 1: TIM5_OC1Init(TIM5_OCMode_PWM1, TIM5_OutputState_Enable, value, TIM5_OCPolarity_High, TIM5_OCIdleState_Set); break; case 2: TIM5_OC2Init(TIM5_OCMode_PWM1, TIM5_OutputState_Enable, value, TIM5_OCPolarity_High, TIM5_OCIdleState_Set); break; default: return; } TIM5_CtrlPWMOutputs(ENABLE); TIM5_Cmd(ENABLE); } else return; #endif } void pwm_stop(PinName pin) { void *peripheral = pinmap_peripheral(pin, PinMap_PWM); if (peripheral == TIM1) { #if defined(STM8Lxx) CLK_PeripheralClockConfig(CLK_Peripheral_TIM1, DISABLE); #endif TIM1_DeInit(); } #ifdef TIM2 else if (peripheral == TIM2) { #if defined(STM8Lxx) CLK_PeripheralClockConfig(CLK_Peripheral_TIM2, DISABLE); #endif TIM2_DeInit(); } #endif #ifdef TIM3 else if (peripheral == TIM3) { #if defined(STM8Lxx) CLK_PeripheralClockConfig(CLK_Peripheral_TIM3, DISABLE); #endif TIM3_DeInit(); } #endif #ifdef TIM5 else if (peripheral == TIM5) { #if defined(STM8Lxx) CLK_PeripheralClockConfig(CLK_Peripheral_TIM5, DISABLE); #endif TIM5_DeInit(); } #endif else { return; } } #ifdef __cplusplus } #endif
SeanGau/Arduino_Core_STM8
cores/arduino/stm8/STM8_StdPeriph_Driver/stm8xx_pwr.c
#if defined (STM8Lxx) #include "stm8l15x_pwr.c" #endif
SeanGau/Arduino_Core_STM8
cores/arduino/stm8/STM8_StdPeriph_Driver/stm8xx_clk.c
#if defined (STM8Sxx) #include "stm8s_clk.c" #elif defined (STM8Lxx) #include "stm8l15x_clk.c" #endif
SeanGau/Arduino_Core_STM8
cores/arduino/stm8/STM8_StdPeriph_Driver/stm8xx_exti.c
#if defined (STM8Sxx) #include "stm8s_exti.c" #elif defined (STM8Lxx) #include "stm8l15x_exti.c" #endif
creffett/statick
tests/plugins/tool/clang-format_tool_plugin/valid_package/indents.c
<reponame>creffett/statick int main() { //this should be indented }
opensalad/logger_plugin
src/abstract_logger.h
#pragma once #include <logger.h> #include <QMap> #include <QString> namespace ad { class AbstractLogger : public Logger<QString, QMap<QString, QString>> { public: enum LoggerFlag { Append = 0x00000001, CleanOnStart = 0x00000002, SplitToFiles = 0x00000003 }; public: AbstractLogger() : __level(LogLevel::All) , __flags(CleanOnStart) {} LogLevel logLevel() const { return __level; } void setLogLevel(LogLevel const level) { __level = level; } void setFlag(LoggerFlag const flag, bool const set = true) { if (!set) __flags &= ~flag; else __flags |= flag; } void setFlags(int const flags) { __flags = flags; } bool getFlag(LoggerFlag const flag) const { return getFlags() & flag; } int getFlags() const { return __flags; } private: LogLevel __level; int __flags; }; }
opensalad/logger_plugin
src/stream_logger.h
<reponame>opensalad/logger_plugin<filename>src/stream_logger.h #pragma once #include "abstract_logger.h" namespace ad { class StreamLogger : public AbstractLogger { public: StreamLogger(); void log(LogLevel level, string_t const &message) override; void setId(string_t const &id) override; void setPattern(string_t const &pattern) override; void setPatternParam(string_t const &param_key, string_t const &param_val) override; void enable() override; void disable() override; void setManager(PluginManager<string_t> *manager) override; string_t id() const override; string_t pattern() const override; string_t param(string_t const &param_key) const override; map_t paramList() const override; string_t uuid() const override; bool isEnabled() const override; protected: virtual void format(LogLevel level, QString &message) const; private: QString __id; QString __pattern; QMap<QString, QString> __params; bool __enabled; }; }
opensalad/logger_plugin
src/file_logger.h
#pragma once #include "logger_global.h" #include "qt_logger.h" #include <QUuid> #include <QFile> namespace ad { class LOGGER_EXPORT FileLogger : public QtLogger { public: FileLogger(); FileLogger(QString const &path); ~FileLogger() override; void setLoggerUuid(QString const &uuid); QString formatMessage(LogLevel level, string_t message) const; void setFilePath(QString const &path); // // Logger interface // void enable() override {} void disable() override {} bool isEnabled() const override { return true; } void log(LogLevel level, string_t const &message) override; void setId(string_t const &id) override; void setPattern(string_t const &pattern) override; void setPatternParam(string_t const &param_key, string_t const &param_val) override; string_t id() const override; string_t pattern() const override; string_t param(string_t const &param_key) const override; map_t paramList() const override; // // Plugin interface // string_t uuid() const override; void setManager(PluginManager<string_t> *) override {} private: QString __uuid; QString __logger_id; QMap<QString, QString> __param_tbl; QString __pattern; QFile __log_file; }; }
opensalad/logger_plugin
src/qt_logger.h
<filename>src/qt_logger.h #pragma once #include "abstract_logger.h" namespace ad { class QtLogger : public AbstractLogger { public: void trace(string_t const& message) { log(LogLevel::Trace, message); } void debug(string_t const& message) { log(LogLevel::Debug, message); } void info(string_t const& message) { log(LogLevel::Info, message); } void warn(string_t const& message) { log(LogLevel::Warn, message); } void error(string_t const& message) { log(LogLevel::Error, message); } }; }
opensalad/logger_plugin
include/logger_factory.h
<reponame>opensalad/logger_plugin #pragma once #include <factory.h> #include <logger.h> #include <QSet> template <typename k, typename v> class QMap; class QString; #define LOGGER(classname) \ static ad::LoggerFactory::logger_t& logger = ad::LoggerFactory::getLoggerFor(#classname) namespace ad { class LoggerFactory { LoggerFactory(); ~LoggerFactory(); public: typedef ad::Logger<QString, QMap<QString, QString>> logger_t; public: logger_t& constructLogger(); void releaseLogger(QString const &logger_id); void setDefaultPattern(QString const &pattern); bool hasLoggerWithID(QString const &id); logger_t& getLoggerWithID(QString const &id); public: static LoggerFactory &global(); static logger_t& getLoggerFor(QString const &classname); static void setPattern(QString const &pattern); static void setLogLevel(LogLevel level); private: QString __default_pattern; LogLevel __default_log_level; QSet<logger_t*> __loggers; }; }
opensalad/logger_plugin
src/invalid_logger.h
#pragma once #include <logger.h> #include <QString> #include <QMap> namespace ad { class InvalidLogger : public Logger<char const *, char const **> { public: void log(LogLevel, string_t const &) override {} void setId(string_t const &) override {} void setPattern(string_t const &) override {} void setPatternParam(string_t const &, string_t const &) override {} void enable() override {} void disable() override {} void setLogLevel(LogLevel level) override {} void setManager(PluginManager<string_t> *) override {} string_t id() const override { return ""; } string_t pattern() const override { return ""; } string_t param(string_t const &) const override { return ""; } map_t paramList() const override { return nullptr; } string_t uuid() const override { return "invalid_logger"; } bool isEnabled() const override { return true; } LogLevel logLevel() const override { return LogLevel::All; } }; }
avinmore/CarTrack
Pods/Target Support Files/Pods-CarTrackTests/Pods-CarTrackTests-umbrella.h
#ifdef __OBJC__ #import <UIKit/UIKit.h> #else #ifndef FOUNDATION_EXPORT #if defined(__cplusplus) #define FOUNDATION_EXPORT extern "C" #else #define FOUNDATION_EXPORT extern #endif #endif #endif FOUNDATION_EXPORT double Pods_CarTrackTestsVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_CarTrackTestsVersionString[];
kikko/ofxKinectForWindows2
src/ofxKinectForWindows2/Source/BodyFrame.h
<reponame>kikko/ofxKinectForWindows2 #pragma once #include "Base.h" #include "../Utils.h" #include "ofMain.h" #include "FaceFrame.h" namespace ofxKinectForWindows2 { enum ProjectionCoordinates { DepthCamera, ColorCamera }; // ------- class Joint { public: Joint(){} Joint(const _Joint& j, const _JointOrientation& jo) { set(j, jo); } void set(const _Joint& j, const _JointOrientation& jo) { joint = j; jOrient = jo; orientation.set(jo.Orientation.x, jo.Orientation.y, jo.Orientation.z, jo.Orientation.w); position.set(j.Position.X, j.Position.Y, j.Position.Z); type = j.JointType; trackingState = j.TrackingState; } JointType getType() const { return type; } ofVec3f getPosition() const { return position; } ofVec2f getProjected(ICoordinateMapper * coordinateMapper, ProjectionCoordinates proj = ColorCamera) const { switch (proj) { case ColorCamera: { ColorSpacePoint projected = { 0 }; coordinateMapper->MapCameraPointToColorSpace(joint.Position, &projected); return ofVec2f(projected.X, projected.Y); } case DepthCamera: { DepthSpacePoint projected = { 0 }; coordinateMapper->MapCameraPointToDepthSpace(joint.Position, &projected); return ofVec2f(projected.X, projected.Y); } } } ofQuaternion getOrientation() const { return orientation; } TrackingState getTrackingState() const { return trackingState; } protected: ofVec3f position; ofQuaternion orientation; JointType type; TrackingState trackingState; _Joint joint; _JointOrientation jOrient; }; // ------- class Body { public: Body::Body(); void clear(); void setTrackHands(bool val); bool isTrackingHands() const; void setTrackFaceProperties(bool val); bool isTrackingFaceProperties() const; UINT64 trackingId; bool tracked; map<JointType, Joint> joints; HandState leftHandState; HandState rightHandState; map<FaceProperty, DetectionResult> faceProperties; private: bool bTrackHands; bool bTrackFaceProperties; }; namespace Source { // ------- class BodyFrame : public Base { public: BodyFrame::~BodyFrame(); string getTypeName() const override; void init(IKinectSensor *) override; void update(); void drawProjected(int x, int y, int width, int height, ProjectionCoordinates proj = ColorCamera); IBodyFrameReader * getReader(); vector<Body> & getBodies(); const vector< pair<JointType, JointType> > & getBonesDef() const; Body * getBodyPtrById(UINT64 trackingId); const Vector4 getFloorClipPlane() { return floorClipPlane; } shared_ptr<FaceFrame> faceFrame; HandState getLeftHandState(const Body & body); HandState getRightHandState(const Body & body); ofMatrix4x4 getFloorTransform(); protected: IKinectSensor* sensor; void drawProjectedBone(map<JointType, Joint> & pJoints, map<JointType, ofVec2f> & pJointPoints, JointType joint0, JointType joint1); void drawProjectedHand(HandState handState, ofVec2f & handPos); void initBonesDefinition(); IBodyFrameReader * reader; ICoordinateMapper * coordinateMapper; IBody* ppBodies[BODY_COUNT]; Vector4 floorClipPlane; vector<Body> bodies; vector< pair<JointType, JointType> > bonesDef; }; } }
kikko/ofxKinectForWindows2
src/ofxKinectForWindows2/Source/FaceFrame.h
#pragma once #include "Base.h" #include "../Utils.h" #include "ofMain.h" #include <Kinect.Face.h> namespace ofxKinectForWindows2 { namespace Source { // ------- class FaceFrame /*: public Base*/ { public: FaceFrame::~FaceFrame(); string getTypeName() const; void init(IKinectSensor *, UINT64 bodyId); void update(); UINT64 getBodyId(){ return bodyId; } IFaceFrameReader * getReader(); map<FaceProperty, DetectionResult> getProperties() { return properties; } string getDebugString(); protected: UINT64 bodyId; map<FaceProperty, DetectionResult> properties; IFaceFrameReader * reader; DetectionResult detectionResults[FaceProperty_Count]; }; } }
kikko/ofxKinectForWindows2
src/ofxKinectForWindows2/Source/VGB.h
#pragma once #include "Base.h" #include "../Utils.h" #include "ofMain.h" #include <Kinect.VisualGestureBuilder.h> namespace ofxKinectForWindows2 { namespace Source { class Gesture { public: Gesture() : gesture(NULL), confidence(0), detected(false), firstFrameDetected(false), progress(0){} // set during init string name; GestureType type; IGesture* gesture; // discrete float confidence; BOOLEAN detected; BOOLEAN firstFrameDetected; // continuous float progress; }; // ------- class VGB { public: VGB::VGB(); VGB::~VGB(); string getTypeName() const; void init(IKinectSensor *, string gbd, UINT64 bodyId = 0); void update(); string getDebugString(); UINT64 getBodyId(){ return bodyId; } void setBodyId(UINT64 bodyId); const vector<shared_ptr<Gesture>> & getGestures() { return gesturesVec; } IVisualGestureBuilderFrameReader * getReader() { return reader; }; IVisualGestureBuilderFrameSource * getSource() { return source; }; IVisualGestureBuilderDatabase * getDatabase() { return vgbd; }; protected: UINT64 bodyId; vector<shared_ptr<Gesture>> gesturesVec; BOOLEAN bTrackingIdValid; UINT numGestures; IGesture** gestures; IVisualGestureBuilderDatabase * vgbd; IVisualGestureBuilderFrameSource * source; IVisualGestureBuilderFrameReader * reader; }; } }
xzwjandyou/Spider
redis-3.2.7/src/version.h
<reponame>xzwjandyou/Spider<gh_stars>0 #define REDIS_VERSION "3.2.7"
EchoZuo/ECAutoScrollBanner
ECAutoScrollBanner/ECAutoScrollBanner.h
// // ECAutoScrollBanner.h // ECAutoScrollBanner // // Created by EchoZuo on 2017/11/21. // Copyright © 2017年 Echo.Z. All rights reserved. // // ********************** 轮播图封装 ********************** // // 轮播图封装。可以实现自动定时翻页、手动翻页;垂直和水平滚动等。支持纯文本、本地图片、网络图片以及其他view试图。 @import UIKit; typedef NS_ENUM(NSInteger, ECAutoScrollBannerScrollDirection){ ECAutoScrollBannerScrollDirectionVertical = 1, // 竖向滚动 ECAutoScrollBannerScrollDirectionHorizontal = 0, // 横向滚动 }; @protocol ECAutoScrollBannerDelegate <NSObject> @optional /** 点击banner @param itemTag tag @param object object */ - (void)tapScrollBannerItem:(NSInteger)itemTag withObject:(id)object; @end @interface ECAutoScrollBanner : UIView /** * delegate,非必 */ @property (nonatomic, weak) id<ECAutoScrollBannerDelegate> delegate; /** * 是否自动翻页,默认NO,非必 */ @property (nonatomic, assign) BOOL isAutoPaging; /** * 是否展示PageControl,默认YES,非必 */ @property (nonatomic, assign) BOOL isHavePageControl; /** * 是否无限循环,默认NO,非必 */ @property (nonatomic, assign) BOOL isInfinitePaging; /** * 自动翻页的时候知否支持手动滑动,必须在isAutoPaging=YES时候设置才有效果,if isAutoPaging=YES,则这个必须设置 */ @property (nonatomic, assign) BOOL isEnabledPanGestureRecognizer; /** * collectionView backgroundColor,默认lightGrayColor,非必 */ @property (nonatomic, strong) UIColor *collectionViewBgColor; /** * 可以自定义pageControl的frame(相对于self),必须isHavePageControl=YES,如果没有设置新坐标,则取默认坐标,非必 */ @property (nonatomic, assign) CGRect pageControlFrame; /** * 自动翻页间隔时间。需isAutoPaging=YES才需要设置,否则设置什么效果。默认3.0f */ @property (nonatomic, assign) CGFloat autoPageInterval; /** 初始化一个文本轮播banner 默认是一个没有无限循环,非自动播放,并且展示pageControl的banner @param frame frame @param textDataSource dataSource @param bannerScrollDirection ECAutoScrollBannerScrollDirection @return id */ + (instancetype)initTextBannerWithFrame:(CGRect)frame withTextDataSource:(NSArray *)textDataSource withBannerScrollDirection:(ECAutoScrollBannerScrollDirection)bannerScrollDirection; - (instancetype)initTextBannerWithFrame:(CGRect)frame withTextDataSource:(NSArray *)textDataSource withBannerScrollDirection:(ECAutoScrollBannerScrollDirection)bannerScrollDirection; /** 初始化一个本地图片轮播banner 默认是一个没有无限循环,非自动播放,并且展示pageControl的banner @param frame frame @param imageDataSource imageDataSource @param bannerScrollDirection ECAutoScrollBannerScrollDirection @return id */ + (instancetype)initLocalImageBannerWithFrame:(CGRect)frame withImageDataSource:(NSArray *)imageDataSource withBannerScrollDirection:(ECAutoScrollBannerScrollDirection)bannerScrollDirection; - (instancetype)initLocalImageBannerWithFrame:(CGRect)frame withImageDataSource:(NSArray *)imageDataSource withBannerScrollDirection:(ECAutoScrollBannerScrollDirection)bannerScrollDirection; /** 初始化一个url图片轮播banner 默认是一个没有无限循环,非自动播放,并且展示pageControl的banner @param frame frame @param imageUrlDataSource imageUrlDataSource @param bannerScrollDirection ECAutoScrollBannerScrollDirection @return id */ + (instancetype)initOnlineImageBannerWithFrame:(CGRect)frame withImageUrlDataSource:(NSArray *)imageUrlDataSource withPlaceholderImage:(UIImage *)placeholderImage withBannerScrollDirection:(ECAutoScrollBannerScrollDirection)bannerScrollDirection; - (instancetype)initOnlineImageBannerWithFrame:(CGRect)frame withImageUrlDataSource:(NSArray *)imageUrlDataSource withPlaceholderImage:(UIImage *)placeholderImage withBannerScrollDirection:(ECAutoScrollBannerScrollDirection)bannerScrollDirection; /** 初始化一个view试图轮播banner @param frame frame @param viewsDataSouce viewsDataSouce @param bannerScrollDirection ECAutoScrollBannerScrollDirection @return id */ + (instancetype)initViewBannerWithFrame:(CGRect)frame withViewsDataSouce:(NSArray *)viewsDataSouce withBannerScrollDirection:(ECAutoScrollBannerScrollDirection)bannerScrollDirection; - (instancetype)initViewBannerWithFrame:(CGRect)frame withViewsDataSouce:(NSArray *)viewsDataSouce withBannerScrollDirection:(ECAutoScrollBannerScrollDirection)bannerScrollDirection; @end
FullOfBytes/Fiwix
mm/memory.c
/* * fiwix/mm/memory.c * * Copyright 2018-2021, <NAME>. All rights reserved. * Distributed under the terms of the Fiwix License. */ #include <fiwix/kernel.h> #include <fiwix/asm.h> #include <fiwix/mm.h> #include <fiwix/mman.h> #include <fiwix/bios.h> #include <fiwix/ramdisk.h> #include <fiwix/process.h> #include <fiwix/buffer.h> #include <fiwix/fs.h> #include <fiwix/filesystems.h> #include <fiwix/stdio.h> #include <fiwix/string.h> #define KERNEL_TEXT_SIZE ((int)_etext - (KERNEL_BASE_ADDR + KERNEL_ENTRY_ADDR)) #define KERNEL_DATA_SIZE ((int)_edata - (int)_etext) #define KERNEL_BSS_SIZE ((int)_end - (int)_edata) #define PGDIR_4MB_ADDR 0x50000 unsigned int *kpage_dir; unsigned int *kpage_table; unsigned int _last_data_addr; unsigned int proc_table_size = 0; struct proc *proc_table; unsigned int buffer_table_size = 0; unsigned int buffer_hash_table_size = 0; struct buffer *buffer_table; struct buffer **buffer_hash_table; unsigned int inode_table_size = 0; unsigned int inode_hash_table_size = 0; struct inode *inode_table; struct inode **inode_hash_table; unsigned int fd_table_size = 0; struct fd *fd_table; unsigned int mount_table_size = 0; struct mount *mount_table; unsigned int page_table_size = 0; unsigned int page_hash_table_size = 0; struct page *page_table; struct page **page_hash_table; static void map_kaddr(unsigned int from, unsigned int to, int flags) { unsigned int n; unsigned int *pgtbl; unsigned int pde, pte; for(n = from >> PAGE_SHIFT; n < (to >> PAGE_SHIFT); n++) { pde = GET_PGDIR(n << PAGE_SHIFT); pte = GET_PGTBL(n << PAGE_SHIFT); if(!(kpage_dir[pde] & ~PAGE_MASK)) { unsigned int addr; addr = _last_data_addr; _last_data_addr += PAGE_SIZE; kpage_dir[pde] = addr | flags; memset_b((void *)addr, NULL, PAGE_SIZE); } pgtbl = (unsigned int *)(kpage_dir[pde] & PAGE_MASK); pgtbl[pte] = (n << PAGE_SHIFT) | flags; } } void bss_init(void) { memset_b((void *)((int)_edata), NULL, KERNEL_BSS_SIZE); } /* * This function creates a minimal Page Directory covering only the first 4MB * of physical memory. Just enough to boot the kernel. * (it returns the address to be used by the CR3 register) */ unsigned int setup_minmem(void) { int n; unsigned int addr; short int pd, mb4; mb4 = 1; /* 4MB units */ addr = KERNEL_BASE_ADDR + PGDIR_4MB_ADDR; kpage_dir = (unsigned int *)addr; memset_b(kpage_dir, NULL, PAGE_SIZE); addr += PAGE_SIZE; kpage_table = (unsigned int *)addr; memset_b(kpage_table, NULL, PAGE_SIZE * mb4); for(n = 0; n < (1024 * mb4); n++) { kpage_table[n] = (n << PAGE_SHIFT) | PAGE_PRESENT | PAGE_RW; if(!(n % 1024)) { pd = n / 1024; kpage_dir[pd] = (unsigned int)(addr + (PAGE_SIZE * pd) + 0x40000000) | PAGE_PRESENT | PAGE_RW; kpage_dir[GET_PGDIR(KERNEL_BASE_ADDR) + pd] = (unsigned int)(addr + (PAGE_SIZE * pd) + 0x40000000) | PAGE_PRESENT | PAGE_RW; } } return (unsigned int)kpage_dir + 0x40000000; } /* returns the mapped address of a virtual address */ unsigned int get_mapped_addr(struct proc *p, unsigned int addr) { unsigned int *pgdir, *pgtbl; unsigned int pde, pte; pgdir = (unsigned int *)P2V(p->tss.cr3); pde = GET_PGDIR(addr); pte = GET_PGTBL(addr); pgtbl = (unsigned int *)P2V((pgdir[pde] & PAGE_MASK)); return pgtbl[pte]; } int clone_pages(struct proc *child) { unsigned int *src_pgdir, *dst_pgdir; unsigned int *src_pgtbl, *dst_pgtbl; unsigned int pde, pte; unsigned int p_addr, c_addr; int n, n2, pages; struct page *pg; struct vma *vma; src_pgdir = (unsigned int *)P2V(current->tss.cr3); dst_pgdir = (unsigned int *)P2V(child->tss.cr3); vma = current->vma; for(n = 0, pages = 0; n < VMA_REGIONS && vma->start; n++, vma++) { for(n2 = vma->start; n2 < vma->end; n2 += PAGE_SIZE) { if(vma->flags & MAP_SHARED) { continue; } pde = GET_PGDIR(n2); pte = GET_PGTBL(n2); if(src_pgdir[pde] & PAGE_PRESENT) { src_pgtbl = (unsigned int *)P2V((src_pgdir[pde] & PAGE_MASK)); if(!(dst_pgdir[pde] & PAGE_PRESENT)) { if(!(c_addr = kmalloc())) { printk("%s(): returning 0!\n", __FUNCTION__); return 0; } current->rss++; pages++; dst_pgdir[pde] = V2P(c_addr) | PAGE_PRESENT | PAGE_RW | PAGE_USER; memset_b((void *)c_addr, NULL, PAGE_SIZE); } dst_pgtbl = (unsigned int *)P2V((dst_pgdir[pde] & PAGE_MASK)); if(src_pgtbl[pte] & PAGE_PRESENT) { p_addr = src_pgtbl[pte] >> PAGE_SHIFT; pg = &page_table[p_addr]; if(pg->flags & PAGE_RESERVED) { continue; } src_pgtbl[pte] &= ~PAGE_RW; /* mark write-only pages as copy-on-write */ if(vma->prot & PROT_WRITE) { pg->flags |= PAGE_COW; } dst_pgtbl[pte] = src_pgtbl[pte]; if(!is_valid_page((dst_pgtbl[pte] & PAGE_MASK) >> PAGE_SHIFT)) { PANIC("%s: missing page %d during copy-on-write process.\n", __FUNCTION__, (dst_pgtbl[pte] & PAGE_MASK) >> PAGE_SHIFT); } pg = &page_table[(dst_pgtbl[pte] & PAGE_MASK) >> PAGE_SHIFT]; pg->count++; } } } } return pages; } int free_page_tables(struct proc *p) { unsigned int *pgdir; int n, count; pgdir = (unsigned int *)P2V(p->tss.cr3); for(n = 0, count = 0; n < PD_ENTRIES; n++) { if((pgdir[n] & (PAGE_PRESENT | PAGE_RW | PAGE_USER)) == (PAGE_PRESENT | PAGE_RW | PAGE_USER)) { kfree(P2V(pgdir[n]) & PAGE_MASK); pgdir[n] = NULL; count++; } } return count; } unsigned int map_page(struct proc *p, unsigned int vaddr, unsigned int addr, unsigned int prot) { unsigned int *pgdir, *pgtbl; unsigned int newaddr; int pde, pte; pgdir = (unsigned int *)P2V(p->tss.cr3); pde = GET_PGDIR(vaddr); pte = GET_PGTBL(vaddr); if(!(pgdir[pde] & PAGE_PRESENT)) { /* allocating page table */ if(!(newaddr = kmalloc())) { return 0; } p->rss++; pgdir[pde] = V2P(newaddr) | PAGE_PRESENT | PAGE_RW | PAGE_USER; memset_b((void *)newaddr, NULL, PAGE_SIZE); } pgtbl = (unsigned int *)P2V((pgdir[pde] & PAGE_MASK)); if(!(pgtbl[pte] & PAGE_PRESENT)) { /* allocating page */ if(!addr) { if(!(addr = kmalloc())) { return 0; } addr = V2P(addr); p->rss++; } pgtbl[pte] = addr | PAGE_PRESENT | PAGE_USER; } if(prot & PROT_WRITE) { pgtbl[pte] |= PAGE_RW; } return P2V(addr); } int unmap_page(unsigned int vaddr) { unsigned int *pgdir, *pgtbl; unsigned int addr; int pde, pte; pgdir = (unsigned int *)P2V(current->tss.cr3); pde = GET_PGDIR(vaddr); pte = GET_PGTBL(vaddr); if(!(pgdir[pde] & PAGE_PRESENT)) { printk("WARNING: %s(): trying to unmap an unallocated pde '0x%08x'\n", __FUNCTION__, vaddr); return 1; } pgtbl = (unsigned int *)P2V((pgdir[pde] & PAGE_MASK)); if(!(pgtbl[pte] & PAGE_PRESENT)) { printk("WARNING: %s(): trying to unmap an unallocated page '0x%08x'\n", __FUNCTION__, vaddr); return 1; } addr = pgtbl[pte] & PAGE_MASK; pgtbl[pte] = NULL; kfree(P2V(addr)); current->rss--; return 0; } void mem_init(void) { unsigned int sizek; unsigned int physical_page_tables; unsigned int physical_memory; int n, pages; physical_page_tables = (kstat.physical_pages / 1024) + ((kstat.physical_pages % 1024) ? 1 : 0); physical_memory = (kstat.physical_pages << PAGE_SHIFT); /* in bytes */ /* Page Directory will be aligned to the next page */ _last_data_addr = PAGE_ALIGN(_last_data_addr); kpage_dir = (unsigned int *)_last_data_addr; memset_b(kpage_dir, NULL, PAGE_SIZE); _last_data_addr += PAGE_SIZE; /* Page Tables */ kpage_table = (unsigned int *)_last_data_addr; memset_b(kpage_table, NULL, physical_page_tables * PAGE_SIZE); _last_data_addr += physical_page_tables * PAGE_SIZE; /* Page Directory and Page Tables initialization */ for(n = 0; n < kstat.physical_pages; n++) { kpage_table[n] = (n << PAGE_SHIFT) | PAGE_PRESENT | PAGE_RW; if(!(n % 1024)) { kpage_dir[GET_PGDIR(KERNEL_BASE_ADDR) + (n / 1024)] = (unsigned int)&kpage_table[n] | PAGE_PRESENT | PAGE_RW; } } map_kaddr(0xA0000, KERNEL_ENTRY_ADDR, PAGE_PRESENT | PAGE_RW); // FIXME: PROVISIONAL (DEBUG IN TIMER)!! map_kaddr(KERNEL_ENTRY_ADDR, _last_data_addr, PAGE_PRESENT | PAGE_RW); /* * FIXME: this is ugly! * It should go in console_init() once we have a proper kernel memory/page management. * Then map_kaddr will be a public function (not static). */ if(video.flags & VPF_VGA) { map_kaddr(0xA0000, 0xA0000 + video.memsize, PAGE_PRESENT | PAGE_RW); }; if(video.flags & VPF_VESAFB) { map_kaddr((unsigned int)video.address, (unsigned int)video.address + video.memsize, PAGE_PRESENT | PAGE_RW); } /* printk("_last_data_addr = 0x%08x-0x%08x (kernel)\n", KERNEL_ENTRY_ADDR, _last_data_addr); */ activate_kpage_dir(); /* since Page Directory is now activated we can use virtual addresses */ _last_data_addr = P2V(_last_data_addr); /* reserve memory space for proc_table[NR_PROCS] */ proc_table_size = PAGE_ALIGN(sizeof(struct proc) * NR_PROCS); if(!addr_in_bios_map(V2P(_last_data_addr) + proc_table_size)) { PANIC("Not enough memory for proc_table.\n"); } /* printk("_last_data_addr = 0x%08x-0x%08x (proc_table)\n", _last_data_addr, _last_data_addr + proc_table_size); */ proc_table = (struct proc *)_last_data_addr; _last_data_addr += proc_table_size; /* reserve memory space for buffer_table */ buffer_table_size = (kstat.physical_pages * BUFFER_PERCENTAGE) / 100; buffer_table_size *= sizeof(struct buffer); pages = buffer_table_size >> PAGE_SHIFT; buffer_table_size = !pages ? 4096 : pages << PAGE_SHIFT; /* printk("_last_data_addr = 0x%08x-0x%08x (buffer_table)\n", _last_data_addr, _last_data_addr + buffer_table_size); */ if(!addr_in_bios_map(V2P(_last_data_addr) + buffer_table_size)) { PANIC("Not enough memory for buffer_table.\n"); } buffer_table = (struct buffer *)_last_data_addr; _last_data_addr += buffer_table_size; /* reserve memory space for buffer_hash_table */ n = (buffer_table_size / sizeof(struct buffer) * BUFFER_HASH_PERCENTAGE) / 100; n = MAX(n, 10); /* 10 buffer hashes as minimum */ /* buffer_hash_table is an array of pointers */ pages = ((n * sizeof(unsigned int)) / PAGE_SIZE) + 1; buffer_hash_table_size = pages << PAGE_SHIFT; /* printk("_last_data_addr = 0x%08x-0x%08x (buffer_hash_table)\n", _last_data_addr, _last_data_addr + buffer_hash_table_size); */ if(!addr_in_bios_map(V2P(_last_data_addr) + buffer_hash_table_size)) { PANIC("Not enough memory for buffer_hash_table.\n"); } buffer_hash_table = (struct buffer **)_last_data_addr; _last_data_addr += buffer_hash_table_size; /* reserve memory space for inode_table */ sizek = physical_memory / 1024; /* this helps to avoid overflow */ inode_table_size = (sizek * INODE_PERCENTAGE) / 100; inode_table_size *= 1024; pages = inode_table_size >> PAGE_SHIFT; inode_table_size = pages << PAGE_SHIFT; /* printk("_last_data_addr = 0x%08x-0x%08x (inode_table)\n", _last_data_addr, _last_data_addr + inode_table_size); */ if(!addr_in_bios_map(V2P(_last_data_addr) + inode_table_size)) { PANIC("Not enough memory for inode_table.\n"); } inode_table = (struct inode *)_last_data_addr; _last_data_addr += inode_table_size; /* reserve memory space for inode_hash_table */ n = ((inode_table_size / sizeof(struct inode)) * INODE_HASH_PERCENTAGE) / 100; n = MAX(n, 10); /* 10 inode hash buckets as minimum */ /* inode_hash_table is an array of pointers */ pages = ((n * sizeof(unsigned int)) / PAGE_SIZE) + 1; inode_hash_table_size = pages << PAGE_SHIFT; /* printk("_last_data_addr = 0x%08x-0x%08x (inode_hash_table)\n", _last_data_addr, _last_data_addr + inode_hash_table_size); */ if(!addr_in_bios_map(V2P(_last_data_addr) + inode_hash_table_size)) { PANIC("Not enough memory for inode_hash_table.\n"); } inode_hash_table = (struct inode **)_last_data_addr; _last_data_addr += inode_hash_table_size; /* reserve memory space for fd_table[NR_OPENS] */ fd_table_size = PAGE_ALIGN(sizeof(struct fd) * NR_OPENS); /* printk("_last_data_addr = 0x%08x-0x%08x (fd_table)\n", _last_data_addr, _last_data_addr + fd_table_size); */ if(!addr_in_bios_map(V2P(_last_data_addr) + fd_table_size)) { PANIC("Not enough memory for fd_table.\n"); } fd_table = (struct fd *)_last_data_addr; _last_data_addr += fd_table_size; /* reserve memory space for mount_table[NR_MOUNT_POINTS] */ mount_table_size = PAGE_ALIGN(sizeof(struct mount) * NR_MOUNT_POINTS); /* printk("_last_data_addr = 0x%08x-0x%08x (mount_table)\n", _last_data_addr, _last_data_addr + mount_table_size); */ if(!addr_in_bios_map(V2P(_last_data_addr) + mount_table_size)) { PANIC("Not enough memory for mount_table.\n"); } mount_table = (struct mount *)_last_data_addr; _last_data_addr += mount_table_size; /* reserve memory space for RAMdisk(s) */ if(!_noramdisk) { if(!_ramdisksize) { _ramdisksize = RAMDISK_SIZE; } /* * If the 'initrd=' parameter was supplied, then the first * ramdisk device was already assigned to the initial ramdisk * image. */ if(ramdisk_table[0].addr) { n = 1; } else { n = 0; } for(; n < RAMDISK_MINORS; n++) { if(!addr_in_bios_map(V2P(_last_data_addr) + (_ramdisksize * 1024))) { printk("WARNING: RAMdisk device disabled (not enough physical memory).\n"); _noramdisk = 1; break; } /* printk("_last_data_addr = 0x%08x-0x%08x (/dev/ram%d)\n", _last_data_addr, _last_data_addr + (_ramdisksize * 1024), n); */ ramdisk_table[n].addr = (char *)_last_data_addr; _last_data_addr += _ramdisksize * 1024; } } /* * FIXME: this is ugly! * It should go in console_init() once we have a proper kernel memory/page management. */ #include <fiwix/console.h> for(n = 1; n <= NR_VCONSOLES; n++) { vc_screen[n] = (short int *)_last_data_addr; _last_data_addr += (video.columns * video.lines * 2); } /* * FIXME: this is ugly! * It should go in console_init() once we have a proper kernel memory/page management. */ vcbuf = (short int *)_last_data_addr; _last_data_addr += (video.columns * video.lines * SCREENS_LOG * 2 * sizeof(short int)); /* the last one must be the page_table structure */ page_hash_table_size = 1 * PAGE_SIZE; /* only 1 page size */ if(!addr_in_bios_map(V2P(_last_data_addr) + page_hash_table_size)) { PANIC("Not enough memory for page_hash_table.\n"); } page_hash_table = (struct page **)_last_data_addr; /* printk("_last_data_addr = 0x%08x-0x%08x (page_hash_table)\n", _last_data_addr, _last_data_addr + page_hash_table_size); */ _last_data_addr += page_hash_table_size; page_table_size = PAGE_ALIGN(kstat.physical_pages * sizeof(struct page)); if(!addr_in_bios_map(V2P(_last_data_addr) + page_table_size)) { PANIC("Not enough memory for page_table.\n"); } page_table = (struct page *)_last_data_addr; /* printk("page_table_size = %d\n", page_table_size); */ /* printk("_last_data_addr = 0x%08x-0x%08x (page_table)\n", _last_data_addr, _last_data_addr + page_table_size); */ _last_data_addr += page_table_size; page_init(kstat.physical_pages); } void mem_stats(void) { printk("\n"); printk("memory: total/available=%dKB/%dKB, kernel=%dKB, reserved=%dKB\n", kstat.physical_pages << 2, kstat.total_mem_pages << 2, kstat.kernel_reserved, kstat.physical_reserved); printk("kernel: text=%dKB, data=%dKB, bss=%dKB, i/o buffers=%d (%dKB)\n", KERNEL_TEXT_SIZE / 1024, KERNEL_DATA_SIZE / 1024, KERNEL_BSS_SIZE / 1024, buffer_table_size / sizeof(struct buffer), (buffer_table_size + buffer_hash_table_size) / 1024); printk("\tinodes=%d (%dKB)\n\n", inode_table_size / sizeof(struct inode), (inode_table_size + inode_hash_table_size) / 1024); }
FullOfBytes/Fiwix
fs/buffer.c
/* * fiwix/fs/buffer.c * * Copyright 2018-2021, <NAME>. All rights reserved. * Distributed under the terms of the Fiwix License. */ /* * buffer.c implements a cache using the LRU (Least Recently Used) algorithm, * with a free list as a doubly circular linked list and a chained hash table * with doubly linked lists. * * hash table * +--------+ +--------------+ +--------------+ +--------------+ * | index | |prev|data|next| |prev|data|next| |prev|data|next| * | 0 --> | / | | ---> <--- | | ---> <--- | | / | * +--------+ +--------------+ +--------------+ +--------------+ * +--------+ +--------------+ +--------------+ +--------------+ * | index | |prev|data|next| |prev|data|next| |prev|data|next| * | 1 --> | / | | ---> <--- | | ---> <--- | | / | * +--------+ +--------------+ +--------------+ +--------------+ * (buffer) (buffer) (buffer) * ... */ #include <fiwix/asm.h> #include <fiwix/kernel.h> #include <fiwix/sleep.h> #include <fiwix/sched.h> #include <fiwix/buffer.h> #include <fiwix/devices.h> #include <fiwix/fs.h> #include <fiwix/mm.h> #include <fiwix/errno.h> #include <fiwix/stdio.h> #include <fiwix/string.h> #include <fiwix/stat.h> #define BUFFER_HASH(dev, block) (((__dev_t)(dev) ^ (__blk_t)(block)) % (NR_BUF_HASH)) #define NR_BUFFERS (buffer_table_size / sizeof(struct buffer)) #define NR_BUF_HASH (buffer_hash_table_size / sizeof(unsigned int)) struct buffer *buffer_table; /* buffer pool */ struct buffer *buffer_head; /* buffer pool head */ struct buffer *buffer_dirty_head; struct buffer **buffer_hash_table; static struct resource sync_resource = { NULL, NULL }; static void insert_to_hash(struct buffer *buf) { struct buffer **h; int i; i = BUFFER_HASH(buf->dev, buf->block); h = &buffer_hash_table[i]; if(!*h) { *h = buf; (*h)->prev_hash = (*h)->next_hash = NULL; } else { buf->prev_hash = NULL; buf->next_hash = *h; (*h)->prev_hash = buf; *h = buf; } } static void remove_from_hash(struct buffer *buf) { struct buffer **h; int i; i = BUFFER_HASH(buf->dev, buf->block); h = &buffer_hash_table[i]; while(*h) { if(*h == buf) { if((*h)->next_hash) { (*h)->next_hash->prev_hash = (*h)->prev_hash; } if((*h)->prev_hash) { (*h)->prev_hash->next_hash = (*h)->next_hash; } if(h == &buffer_hash_table[i]) { *h = (*h)->next_hash; } break; } h = &(*h)->next_hash; } } static void insert_on_dirty_list(struct buffer *buf) { if(buf->prev_dirty || buf->next_dirty) { return; } if(buffer_dirty_head) { buf->next_dirty = buffer_dirty_head; buffer_dirty_head->prev_dirty = buf; } buffer_dirty_head = buf; kstat.dirty += (PAGE_SIZE / 1024); } static void remove_from_dirty_list(struct buffer *buf) { if(buf->next_dirty) { buf->next_dirty->prev_dirty = buf->prev_dirty; } if(buf->prev_dirty) { buf->prev_dirty->next_dirty = buf->next_dirty; } if(buf == buffer_dirty_head) { buffer_dirty_head = buf->next_dirty; } buf->prev_dirty = buf->next_dirty = NULL; buf->flags &= ~BUFFER_DIRTY; kstat.dirty -= (PAGE_SIZE / 1024); } static void insert_on_free_list(struct buffer *buf) { if(!buffer_head) { buf->prev_free = buf->next_free = buf; buffer_head = buf; } else { buf->next_free = buffer_head; buf->prev_free = buffer_head->prev_free; buffer_head->prev_free->next_free = buf; buffer_head->prev_free = buf; /* * If is marked as not valid then the buffer is * placed at the beginning of the free list. */ if(!(buf->flags & BUFFER_VALID)) { buffer_head = buf; } } } static void remove_from_free_list(struct buffer *buf) { if(!buffer_head) { return; } buf->prev_free->next_free = buf->next_free; buf->next_free->prev_free = buf->prev_free; if(buf == buffer_head) { buffer_head = buf->next_free; } if(buffer_head == buffer_head->next_free) { buffer_head = NULL; } } static void buffer_wait(struct buffer *buf) { unsigned long int flags; for(;;) { SAVE_FLAGS(flags); CLI(); if(buf->flags & BUFFER_LOCKED) { RESTORE_FLAGS(flags); sleep(&buffer_wait, PROC_UNINTERRUPTIBLE); } else { break; } } buf->flags |= BUFFER_LOCKED; RESTORE_FLAGS(flags); } static struct buffer * get_free_buffer(void) { unsigned long int flags; struct buffer *buf; /* no more buffers on free list */ if(!buffer_head) { return NULL; } for(;;) { SAVE_FLAGS(flags); CLI(); buf = buffer_head; if(buf->flags & BUFFER_LOCKED) { RESTORE_FLAGS(flags); sleep(&buffer_wait, PROC_UNINTERRUPTIBLE); } else { break; } } remove_from_free_list(buf); buf->flags |= BUFFER_LOCKED; RESTORE_FLAGS(flags); return buf; } static void sync_one_buffer(struct buffer *buf) { struct device *d; int errno; if(!(d = get_device(BLK_DEV, buf->dev))) { printk("WARNING: %s(): block device %d,%d not registered!\n", __FUNCTION__, MAJOR(buf->dev), MINOR(buf->dev)); return; } if(d->fsop && d->fsop->write_block) { errno = d->fsop->write_block(buf->dev, buf->block, buf->data, buf->size); if(errno < 0) { if(errno == -EROFS) { printk("WARNING: %s(): write protection on device %d,%d.\n", __FUNCTION__, MAJOR(buf->dev), MINOR(buf->dev), buf->block); } else { printk("WARNING: %s(): I/O error on device %d,%d.\n", __FUNCTION__, MAJOR(buf->dev), MINOR(buf->dev), buf->block); } return; } remove_from_dirty_list(buf); } else { printk("WARNING: %s(): device %d,%d does not have the write_block() method!\n", __FUNCTION__, MAJOR(buf->dev), MINOR(buf->dev)); } } static struct buffer * search_buffer_hash(__dev_t dev, __blk_t block, int size) { struct buffer *buf; int i; i = BUFFER_HASH(dev, block); buf = buffer_hash_table[i]; while(buf) { if(buf->dev == dev && buf->block == block && buf->size == size) { return buf; } buf = buf->next_hash; } return NULL; } static struct buffer * getblk(__dev_t dev, __blk_t block, int size) { unsigned long int flags; struct buffer *buf; for(;;) { if((buf = search_buffer_hash(dev, block, size))) { SAVE_FLAGS(flags); CLI(); if(buf->flags & BUFFER_LOCKED) { RESTORE_FLAGS(flags); sleep(&buffer_wait, PROC_UNINTERRUPTIBLE); continue; } buf->flags |= BUFFER_LOCKED; remove_from_free_list(buf); RESTORE_FLAGS(flags); return buf; } if(!(buf = get_free_buffer())) { printk("WARNING: %s(): no more buffers on free list!\n", __FUNCTION__); sleep(&get_free_buffer, PROC_UNINTERRUPTIBLE); continue; } if(buf->flags & BUFFER_DIRTY) { sync_one_buffer(buf); } else { if(!buf->data) { if(!(buf->data = (char *)kmalloc())) { brelse(buf); printk("%s(): returning NULL\n", __FUNCTION__); return NULL; } kstat.buffers += (PAGE_SIZE / 1024); } } SAVE_FLAGS(flags); CLI(); remove_from_hash(buf); /* remove it from old hash */ buf->dev = dev; buf->block = block; buf->size = size; insert_to_hash(buf); buf->flags &= ~BUFFER_VALID; RESTORE_FLAGS(flags); return buf; } } struct buffer * bread(__dev_t dev, __blk_t block, int size) { struct buffer *buf; struct device *d; if(!(d = get_device(BLK_DEV, dev))) { printk("WARNING: %s(): device major %d not found!\n", __FUNCTION__, MAJOR(dev)); return NULL; } if((buf = getblk(dev, block, size))) { if(!(buf->flags & BUFFER_VALID)) { if(d->fsop && d->fsop->read_block) { if(d->fsop->read_block(dev, block, buf->data, size) >= 0) { buf->flags |= BUFFER_VALID; } } } if(buf->flags & BUFFER_VALID) { return buf; } brelse(buf); } printk("WARNING: %s(): returning NULL!\n", __FUNCTION__); return NULL; } void bwrite(struct buffer *buf) { buf->flags |= (BUFFER_DIRTY | BUFFER_VALID); brelse(buf); } void brelse(struct buffer *buf) { unsigned long int flags; SAVE_FLAGS(flags); CLI(); if(buf->flags & BUFFER_DIRTY) { insert_on_dirty_list(buf); } insert_on_free_list(buf); buf->flags &= ~BUFFER_LOCKED; RESTORE_FLAGS(flags); wakeup(&get_free_buffer); wakeup(&buffer_wait); } void sync_buffers(__dev_t dev) { struct buffer *buf, *next; buf = buffer_dirty_head; lock_resource(&sync_resource); while(buf) { next = buf->next_dirty; if(!dev || buf->dev == dev) { buffer_wait(buf); sync_one_buffer(buf); buf->flags &= ~BUFFER_LOCKED; wakeup(&buffer_wait); } buf = next; } unlock_resource(&sync_resource); } void invalidate_buffers(__dev_t dev) { unsigned long int flags; unsigned int n; struct buffer *buf; buf = &buffer_table[0]; SAVE_FLAGS(flags); CLI(); for(n = 0; n < NR_BUFFERS; n++) { if(!(buf->flags & BUFFER_LOCKED) && buf->dev == dev) { buffer_wait(buf); remove_from_hash(buf); buf->flags &= ~(BUFFER_VALID | BUFFER_LOCKED); wakeup(&buffer_wait); } buf++; } RESTORE_FLAGS(flags); /* FIXME: invalidate_pages(dev); */ } /* * When kernel runs out of pages, kswapd is awaken and it calls this function * which goes throught the buffer cache, freeing up to NR_BUF_RECLAIM buffers. */ int reclaim_buffers(void) { struct buffer *buf, *first; int reclaimed; reclaimed = 0; first = NULL; for(;;) { if(!(buf = get_free_buffer())) { printk("WARNING: %s(): no more buffers on free list!\n", __FUNCTION__); sleep(&get_free_buffer, PROC_UNINTERRUPTIBLE); continue; } if(buf->flags & BUFFER_DIRTY) { sync_one_buffer(buf); } /* this ensures the buffer will go to the tail */ buf->flags |= BUFFER_VALID; if(first) { if(first == buf) { brelse(buf); break; } } else { first = buf; } if(buf->data) { kfree((unsigned int)buf->data); buf->data = NULL; remove_from_hash(buf); kstat.buffers -= (PAGE_SIZE / 1024); reclaimed++; if(reclaimed == NR_BUF_RECLAIM) { brelse(buf); break; } } brelse(buf); } wakeup(&buffer_wait); /* * If the total number of buffers reclaimed was less or equal to * NR_BUF_RECLAIM, then wakeup any process waiting for a new page * because release_page() won't do it. */ if(reclaimed && reclaimed <= NR_BUF_RECLAIM) { wakeup(&get_free_page); } return reclaimed; } void buffer_init(void) { struct buffer *buf; unsigned int n; memset_b(buffer_table, NULL, buffer_table_size); memset_b(buffer_hash_table, NULL, buffer_hash_table_size); for(n = 0; n < NR_BUFFERS; n++) { buf = &buffer_table[n]; insert_on_free_list(buf); } }
FullOfBytes/Fiwix
include/fiwix/sysrq.h
/* * fiwix/include/fiwix/sysrq.h * * Copyright 2021, <NAME>. All rights reserved. * Distributed under the terms of the Fiwix License. */ #ifndef _FIWIX_SYSRQ_H #define _FIWIX_SYSRQ_H #define SYSRQ_STACK 0x00000002 /* Stack backtrace */ #define SYSRQ_TASKS 0x00000004 /* Task list */ #define SYSRQ_UNDEF 0x80000000 /* Undefined operation */ void do_sysrq(int); #endif /* _FIWIX_SYSRQ_H */
FullOfBytes/Fiwix
drivers/char/console.c
<reponame>FullOfBytes/Fiwix /* * fiwix/drivers/char/console.c * * Copyright 2018-2021, <NAME>. All rights reserved. * Distributed under the terms of the Fiwix License. */ #include <fiwix/asm.h> #include <fiwix/kernel.h> #include <fiwix/ctype.h> #include <fiwix/console.h> #include <fiwix/devices.h> #include <fiwix/tty.h> #include <fiwix/keyboard.h> #include <fiwix/sleep.h> #include <fiwix/pit.h> #include <fiwix/timer.h> #include <fiwix/process.h> #include <fiwix/mm.h> #include <fiwix/sched.h> #include <fiwix/kd.h> #include <fiwix/stdio.h> #include <fiwix/string.h> #include <fiwix/fbcon.h> #define CSI_J_CUR2END 0 /* clear from cursor to end of screen */ #define CSI_J_STA2CUR 1 /* clear from start of screen to cursor */ #define CSI_J_SCREEN 2 /* clear entire screen */ #define CSI_K_CUR2END 0 /* clear from cursor to end of line */ #define CSI_K_STA2CUR 1 /* clear from start of line to cursor */ #define CSI_K_LINE 2 /* clear entire line */ #define CSE vc->esc = 0 /* Code Set End */ /* VT100 ID string generated by <ESC>Z or <ESC>[c */ #define VT100ID "\033[?1;2c" /* VT100 report status generated by <ESC>[5n */ #define DEVICE_OK "\033[0n" #define DEVICE_NOT_OK "\033[3n" #define SCREEN_SIZE (video.columns * video.lines) #define VC_BUF_LINES (video.lines * SCREENS_LOG) short int current_cons; struct video_parms video; struct vconsole vc[NR_VCONSOLES + 1]; static struct fs_operations tty_driver_fsop = { 0, 0, tty_open, tty_close, tty_read, tty_write, tty_ioctl, tty_lseek, NULL, /* readdir */ NULL, /* mmap */ tty_select, NULL, /* readlink */ NULL, /* followlink */ NULL, /* bmap */ NULL, /* lookup */ NULL, /* rmdir */ NULL, /* link */ NULL, /* unlink */ NULL, /* symlink */ NULL, /* mkdir */ NULL, /* mknod */ NULL, /* truncate */ NULL, /* create */ NULL, /* rename */ NULL, /* read_block */ NULL, /* write_block */ NULL, /* read_inode */ NULL, /* write_inode */ NULL, /* ialloc */ NULL, /* ifree */ NULL, /* statfs */ NULL, /* read_superblock */ NULL, /* remount_fs */ NULL, /* write_superblock */ NULL /* release_superblock */ }; static struct device tty_device = { "vconsole", VCONSOLES_MAJOR, { 0, 0, 0, 0, 0, 0, 0, 0 }, 0, NULL, &tty_driver_fsop, NULL }; static struct device console_device = { "console", SYSCON_MAJOR, { 0, 0, 0, 0, 0, 0, 0, 0 }, 0, NULL, &tty_driver_fsop, NULL }; unsigned short int ansi_color_table[] = { COLOR_BLACK, COLOR_RED, COLOR_GREEN, COLOR_BROWN, COLOR_BLUE, COLOR_MAGENTA, COLOR_CYAN, COLOR_WHITE }; static int is_vconsole(__dev_t dev) { if(MAJOR(dev) == VCONSOLES_MAJOR && MINOR(dev) <= NR_VCONSOLES) { return 1; } return 0; } static void adjust(struct vconsole *vc, int x, int y) { if(x < 0) { x = 0; } if(x >= vc->columns) { x = vc->columns - 1; } if(y < 0) { y = 0; } if(y >= vc->lines) { y = vc->lines - 1; } vc->x = x; vc->y = y; } static void cr(struct vconsole *vc) { vc->x = 0; } static void lf(struct vconsole *vc) { if(vc->y == vc->lines) { video.scroll_screen(vc, 0, SCROLL_UP); } else { vc->y++; } } static void ri(struct vconsole *vc) { if(vc->y == 0) { video.scroll_screen(vc, 0, SCROLL_DOWN); } else { vc->y--; } } static void csi_J(struct vconsole *vc, int mode) { int from, count; switch(mode) { case CSI_J_CUR2END: /* Erase Down <ESC>[J */ from = (vc->y * vc->columns) + vc->x; count = vc->columns - vc->x; video.write_screen(vc, from, count, vc->color_attr); from = ((vc->y + 1) * vc->columns); count = SCREEN_SIZE - from; break; case CSI_J_STA2CUR: /* Erase Up <ESC>[1J */ from = vc->y * vc->columns; count = vc->x + 1; video.write_screen(vc, from, count, vc->color_attr); from = 0; count = vc->y * vc->columns; break; case CSI_J_SCREEN: /* Erase Screen <ESC>[2J */ from = 0; count = SCREEN_SIZE; break; default: return; } video.write_screen(vc, from, count, vc->color_attr); } static void csi_K(struct vconsole *vc, int mode) { int from, count; switch(mode) { case CSI_K_CUR2END: /* Erase End of Line <ESC>[K */ from = (vc->y * vc->columns) + vc->x; count = vc->columns - vc->x; break; case CSI_K_STA2CUR: /* Erase Start of Line <ESC>[1K */ from = vc->y * vc->columns; count = vc->x + 1; break; case CSI_K_LINE: /* Erase Line <ESC>[2K */ from = vc->y * vc->columns; count = vc->columns; break; default: return; } video.write_screen(vc, from, count, vc->color_attr); } static void csi_X(struct vconsole *vc, int count) { int from; from = (vc->y * vc->columns) + vc->x; count = count > (vc->columns - vc->x) ? vc->columns - vc->x : count; video.write_screen(vc, from, count, vc->color_attr); } static void csi_L(struct vconsole *vc, int count) { if(count > (vc->lines - vc->top)) { count = vc->lines - vc->top; } while(count--) { video.scroll_screen(vc, vc->y, SCROLL_DOWN); } } static void csi_M(struct vconsole *vc, int count) { if(count > (vc->lines - vc->top)) { count = vc->lines - vc->top; } while(count--) { video.scroll_screen(vc, vc->y, SCROLL_UP); } } static void csi_P(struct vconsole *vc, int count) { if(count > vc->columns) { count = vc->columns; } while(count--) { video.delete_char(vc); } } static void csi_at(struct vconsole *vc, int count) { if(count > vc->columns) { count = vc->columns; } while(count--) { video.insert_char(vc); } } static void default_color_attr(struct vconsole *vc) { vc->color_attr = DEF_MODE; vc->bold = 0; vc->underline = 0; vc->blink = 0; vc->reverse = 0; } /* Select Graphic Rendition */ static void csi_m(struct vconsole *vc) { int n; if(vc->reverse) { vc->color_attr = ((vc->color_attr & 0x7000) >> 4) | ((vc->color_attr & 0x0700) << 4) | (vc->color_attr & 0x8800); } for(n = 0; n < vc->nparms; n++) { switch(vc->parms[n]) { case SGR_DEFAULT: default_color_attr(vc); break; case SGR_BOLD: vc->bold = 1; break; case SGR_BLINK: vc->blink = 1; break; case SGR_REVERSE: vc->reverse = 1; break; /* normal intensity */ case 21: case 22: vc->bold = 0; break; case SGR_BLINK_OFF: vc->blink = 0; break; case SGR_REVERSE_OFF: vc->reverse = 0; break; case SGR_BLACK_FG: case SGR_RED_FG: case SGR_GREEN_FG: case SGR_BROWN_FG: case SGR_BLUE_FG: case SGR_MAGENTA_FG: case SGR_CYAN_FG: case SGR_WHITE_FG: vc->color_attr = (vc->color_attr & 0xF8FF) | (ansi_color_table[vc->parms[n] - 30]); break; case SGR_DEFAULT_FG_U_ON: case SGR_DEFAULT_FG_U_OFF: /* not supported yet */ break; case SGR_BLACK_BG: case SGR_RED_BG: case SGR_GREEN_BG: case SGR_BROWN_BG: case SGR_BLUE_BG: case SGR_MAGENTA_BG: case SGR_CYAN_BG: case SGR_WHITE_BG: vc->color_attr = (vc->color_attr & 0x8FFF) | ((ansi_color_table[vc->parms[n] - 40]) << 4); break; case SGR_DEFAULT_BG: /* not supported yet */ break; } } if(vc->bold) { vc->color_attr |= 0x0800; } else { vc->color_attr &= ~0x0800; } if(vc->blink) { vc->color_attr |= 0x8000; } else { vc->color_attr &= ~0x8000; } if(vc->reverse) { vc->color_attr = ((vc->color_attr & 0x7000) >> 4) | ((vc->color_attr & 0x0700) << 4) | (vc->color_attr & 0x8800); } } static void init_vt(struct vconsole *vc) { vc->vt_mode.mode = VT_AUTO; vc->vt_mode.waitv = 0; vc->vt_mode.relsig = 0; vc->vt_mode.acqsig = 0; vc->vt_mode.frsig = 0; vc->vc_mode = KD_TEXT; vc->tty->pid = 0; vc->switchto_tty = -1; } static void insert_seq(struct tty *tty, char *buf, int count) { while(count--) { tty_queue_putchar(tty, &tty->read_q, *(buf++)); } tty->input(tty); } static void vcbuf_scroll_up(void) { memcpy_w(vcbuf, vcbuf + video.columns, (VC_BUF_SIZE - video.columns) * 2); } static void vcbuf_refresh(struct vconsole *vc) { short int *screen; screen = (short int *)vc->screen; memset_w(vcbuf, BLANK_MEM, VC_BUF_SIZE); memcpy_w(vcbuf, screen, SCREEN_SIZE); } static void echo_char(struct vconsole *vc, unsigned char *buf, unsigned int count) { unsigned char ch; unsigned long int flags; SAVE_FLAGS(flags); CLI(); if(vc->flags & CONSOLE_HAS_FOCUS) { if(video.buf_top) { video.restore_screen(vc); video.show_cursor(vc, ON); video.buf_top = 0; } } while(count--) { ch = *buf++; if(ch == NULL) { continue; } else if(ch == '\b') { if(vc->x) { vc->x--; } } else if(ch == '\a') { vconsole_beep(); } else if(ch == '\r') { cr(vc); } else if(ch == '\n') { cr(vc); vc->y++; if(vc->flags & CONSOLE_HAS_FOCUS) { video.buf_y++; } } else if(ch == '\t') { while(vc->x < (vc->columns - 1)) { if(vc->tty->tab_stop[++vc->x]) { break; } } /* vc->x += TAB_SIZE - (vc->x % TAB_SIZE); */ vc->check_x = 1; } else { if((vc->x == vc->columns - 1) && vc->check_x) { vc->x = 0; vc->y++; if(vc->flags & CONSOLE_HAS_FOCUS) { video.buf_y++; } } if(vc->y >= vc->lines) { video.scroll_screen(vc, 0, SCROLL_UP); vc->y--; } video.put_char(vc, ch); if(vc->x < vc->columns - 1) { vc->check_x = 0; vc->x++; } else { vc->check_x = 1; } } if(vc->y >= vc->lines) { video.scroll_screen(vc, 0, SCROLL_UP); vc->y--; } if(vc->flags & CONSOLE_HAS_FOCUS) { if(video.buf_y >= VC_BUF_LINES) { vcbuf_scroll_up(); video.buf_y--; } } } video.update_curpos(vc); RESTORE_FLAGS(flags); } void vconsole_reset(struct tty *tty) { int n; struct vconsole *vc; vc = (struct vconsole *)tty->driver_data; vc->top = 0; vc->lines = video.lines; vc->columns = video.columns; vc->check_x = 0; vc->led_status = 0; set_leds(vc->led_status); vc->scrlock = vc->numlock = vc->capslock = 0; vc->esc = vc->sbracket = vc->semicolon = vc->question = 0; vc->parmv1 = vc->parmv2 = 0; vc->nparms = 0; memset_b(vc->parms, 0, sizeof(vc->parms)); default_color_attr(vc); vc->insert_mode = 0; vc->saved_x = vc->saved_y = 0; for(n = 0; n < MAX_TAB_COLS; n++) { if(!(n % TAB_SIZE)) { vc->tty->tab_stop[n] = 1; } else { vc->tty->tab_stop[n] = 0; } } termios_reset(tty); vc->tty->winsize.ws_row = vc->lines - vc->top; vc->tty->winsize.ws_col = vc->columns; vc->tty->winsize.ws_xpixel = 0; vc->tty->winsize.ws_ypixel = 0; vc->tty->lnext = 0; init_vt(vc); vc->flags &= ~CONSOLE_BLANKED; video.update_curpos(vc); } void vconsole_write(struct tty *tty) { int n; unsigned char ch; int numeric; struct vconsole *vc; vc = (struct vconsole *)tty->driver_data; if(vc->flags & CONSOLE_HAS_FOCUS) { if(video.buf_top) { video.restore_screen(vc); video.buf_top = 0; video.show_cursor(vc, ON); video.update_curpos(vc); } } ch = numeric = 0; while(!vc->scrlock && tty->write_q.count > 0) { ch = tty_queue_getchar(&tty->write_q); if(vc->esc) { if(vc->sbracket) { if(IS_NUMERIC(ch)) { numeric = 1; if(vc->semicolon) { vc->parmv2 *= 10; vc->parmv2 += ch - '0'; } else { vc->parmv1 *= 10; vc->parmv1 += ch - '0'; } vc->parms[vc->nparms] *= 10; vc->parms[vc->nparms] += ch - '0'; continue; } switch(ch) { case ';': vc->semicolon = 1; vc->parmv2 = 0; vc->nparms++; continue; case '?': vc->question = 1; continue; case '@': /* Insert Character(s) <ESC>[ n @ */ vc->parmv1 = !vc->parmv1 ? 1 : vc->parmv1; csi_at(vc, vc->parmv1); CSE; continue; case 'A': /* Cursor Up <ESC>[ n A */ vc->parmv1 = !vc->parmv1 ? 1 : vc->parmv1; adjust(vc, vc->x, vc->y - vc->parmv1); CSE; continue; case 'B': /* Cursor Down <ESC>[ n B */ vc->parmv1 = !vc->parmv1 ? 1 : vc->parmv1; adjust(vc, vc->x, vc->y + vc->parmv1); CSE; continue; case 'C': /* Cursor Forward <ESC>[ n C */ vc->parmv1 = !vc->parmv1 ? 1 : vc->parmv1; adjust(vc, vc->x + vc->parmv1, vc->y); CSE; continue; case 'D': /* Cursor Backward <ESC>[ n D */ vc->parmv1 = !vc->parmv1 ? 1 : vc->parmv1; adjust(vc, vc->x - vc->parmv1, vc->y); CSE; continue; case 'E': /* Cursor Next Line(s) <ESC>[ n E */ vc->parmv1 = !vc->parmv1 ? 1 : vc->parmv1; adjust(vc, 0, vc->y + vc->parmv1); CSE; continue; case 'F': /* Cursor Previous Line(s) <ESC>[ n F */ vc->parmv1 = !vc->parmv1 ? 1 : vc->parmv1; adjust(vc, 0, vc->y - vc->parmv1); CSE; continue; case 'G': /* Cursor Horizontal Position <ESC>[ n G */ case '`': vc->parmv1 = vc->parmv1 ? vc->parmv1 - 1 : vc->parmv1; adjust(vc, vc->parmv1, vc->y); CSE; continue; case 'H': /* Cursor Home <ESC>[ ROW ; COLUMN H */ case 'f': /* Horizontal Vertical Position <ESC>[ ROW ; COLUMN f */ vc->parmv1 = vc->parmv1 ? vc->parmv1 - 1 : vc->parmv1; vc->parmv2 = vc->parmv2 ? vc->parmv2 - 1 : vc->parmv2; adjust(vc, vc->parmv2, vc->parmv1); CSE; continue; case 'I': /* Cursor Forward Tabulation <ESC>[ n I */ vc->parmv1 = !vc->parmv1 ? 1 : vc->parmv1; while(vc->parmv1--){ while(vc->x < (vc->columns - 1)) { if(vc->tty->tab_stop[++vc->x]) { break; } } } adjust(vc, vc->x, vc->y); CSE; continue; case 'J': /* Erase (Down/Up/Screen) <ESC>[J */ csi_J(vc, vc->parmv1); CSE; continue; case 'K': /* Erase (End of/Start of/) Line <ESC>[K */ csi_K(vc, vc->parmv1); CSE; continue; case 'L': /* Insert Line(s) <ESC>[ n L */ vc->parmv1 = !vc->parmv1 ? 1 : vc->parmv1; csi_L(vc, vc->parmv1); CSE; continue; case 'M': /* Delete Line(s) <ESC>[ n M */ vc->parmv1 = !vc->parmv1 ? 1 : vc->parmv1; csi_M(vc, vc->parmv1); CSE; continue; case 'P': /* Delete Character(s) <ESC>[ n P */ vc->parmv1 = !vc->parmv1 ? 1 : vc->parmv1; csi_P(vc, vc->parmv1); CSE; continue; case 'S': /* Scroll Up <ESC>[ n S */ vc->parmv1 = !vc->parmv1 ? 1 : vc->parmv1; while(vc->parmv1--) { video.scroll_screen(vc, 0, SCROLL_UP); } CSE; continue; case 'T': /* Scroll Down <ESC>[ n T */ vc->parmv1 = !vc->parmv1 ? 1 : vc->parmv1; while(vc->parmv1--) { video.scroll_screen(vc, 0, SCROLL_DOWN); } CSE; continue; case 'X': /* Erase Character(s) <ESC>[ n X */ vc->parmv1 = !vc->parmv1 ? 1 : vc->parmv1; csi_X(vc, vc->parmv1); CSE; continue; case 'c': /* Query Device Code <ESC>[c */ if(!numeric) { insert_seq(tty, VT100ID, 7); } CSE; continue; case 'd': /* Cursor Vertical Position <ESC>[ n d */ vc->parmv1 = vc->parmv1 ? vc->parmv1 - 1 : vc->parmv1; adjust(vc, vc->x, vc->parmv1); CSE; continue; case 'g': switch(vc->parmv1) { case 0: /* Clear Tab <ESC>[g */ vc->tty->tab_stop[vc->x] = 0; break; case 3: /* Clear All Tabs <ESC>[3g */ case 5: /* Clear All Tabs <ESC>[5g */ for(n = 0; n < MAX_TAB_COLS; n++) vc->tty->tab_stop[n] = 0; break; } CSE; continue; case 'h': if(vc->question) { switch(vc->parmv1) { /* DEC modes */ case 25: /* Switch Cursor Visible <ESC>[?25h */ video.show_cursor(vc, ON); break; case 4: vc->insert_mode = ON; /* not used */ break; } } CSE; continue; case 'l': if(vc->question) { switch(vc->parmv1) { /* DEC modes */ case 25: /* Switch Cursor Invisible <ESC>[?25l */ video.show_cursor(vc, OFF); break; case 4: vc->insert_mode = OFF; /* not used */ break; } } CSE; continue; case 'm': /* Select Graphic Rendition <ESC> n ... m */ vc->nparms++; csi_m(vc); CSE; continue; case 'n': if(!vc->question) { switch(vc->parmv1) { case 5: /* Query Device Status <ESC>[5n */ insert_seq(tty, DEVICE_OK, 4); break; case 6: /* Query Cursor Position <ESC>[6n */ { char curpos[8]; char len; len = sprintk(curpos, "\033[%d;%dR", vc->y, vc->x); insert_seq(tty, curpos, len); } break; } } CSE; continue; case 'r': /* Top and Bottom Margins <ESC>[r / <ESC>[{start};{end}r */ if(!vc->parmv1) { vc->parmv1++; } if(!vc->parmv2) { vc->parmv2 = video.lines; } if(vc->parmv1 < vc->parmv2 && vc->parmv2 <= video.lines) { vc->top = vc->parmv1 - 1; vc->lines = vc->parmv2; adjust(vc, 0, 0); } CSE; continue; case 's': /* Save Cursor <ESC>[s */ vc->saved_x = vc->x; vc->saved_y = vc->y; CSE; continue; case 'u': /* Restore Cursor <ESC>[u */ vc->x = vc->saved_x; vc->y = vc->saved_y; CSE; continue; default: CSE; break; } } else { switch(ch) { case '[': vc->sbracket = 1; vc->semicolon = 0; vc->question = 0; vc->parmv1 = vc->parmv2 = 0; vc->nparms = 0; memset_b(vc->parms, 0, sizeof(vc->parms)); continue; case '7': /* Save Cursor & Attrs <ESC>7 */ vc->saved_x = vc->x; vc->saved_y = vc->y; CSE; continue; case '8': /* Restore Cursor & Attrs <ESC>8 */ vc->x = vc->saved_x; vc->y = vc->saved_y; CSE; continue; case 'D': /* Scroll Up <ESC>D */ lf(vc); CSE; continue; case 'E': /* Move To Next Line <ESC>E */ cr(vc); lf(vc); CSE; continue; case 'H': /* Set Tab <ESC>H */ vc->tty->tab_stop[vc->x] = 1; CSE; continue; case 'M': /* Scroll Down <ESC>M */ ri(vc); CSE; continue; case 'Z': /* Identify Terminal <ESC>Z */ insert_seq(tty, VT100ID, 7); CSE; continue; case 'c': /* Reset Device <ESC>c */ vconsole_reset(vc->tty); vc->x = vc->y = 0; csi_J(vc, CSI_J_SCREEN); CSE; continue; default: CSE; break; } } } switch(ch) { case '\033': vc->esc = 1; vc->sbracket = 0; vc->semicolon = 0; vc->question = 0; vc->parmv1 = vc->parmv2 = 0; continue; default: echo_char(vc, &ch, 1); continue; } } if(ch) { if(vc->vc_mode != KD_GRAPHICS) { video.update_curpos(vc); } wakeup(&tty_write); } } void vconsole_select(int new_cons) { new_cons++; if(current_cons != new_cons) { if(vc[current_cons].vt_mode.mode == VT_PROCESS) { if(!kill_pid(vc[current_cons].tty->pid, vc[current_cons].vt_mode.acqsig)) { vc[current_cons].switchto_tty = new_cons; return; } init_vt(&vc[current_cons]); } if(vc[current_cons].vc_mode == KD_GRAPHICS) { return; } vconsole_select_final(new_cons); } } void vconsole_select_final(int new_cons) { if(current_cons != new_cons) { if(vc[new_cons].vt_mode.mode == VT_PROCESS) { if(kill_pid(vc[new_cons].tty->pid, vc[new_cons].vt_mode.acqsig)) { init_vt(&vc[new_cons]); } } if(video.buf_top) { video.buf_top = 0; video.show_cursor(&vc[current_cons], ON); video.update_curpos(&vc[current_cons]); } vc[current_cons].vidmem = NULL; vc[current_cons].flags &= ~CONSOLE_HAS_FOCUS; vc[new_cons].vidmem = (unsigned char *)video.address; vc[new_cons].flags |= CONSOLE_HAS_FOCUS; video.restore_screen(&vc[new_cons]); current_cons = new_cons; set_leds(vc[current_cons].led_status); video.update_curpos(&vc[current_cons]); video.buf_y = vc[current_cons].y; video.buf_top = 0; vcbuf_refresh(&vc[current_cons]); video.show_cursor(&vc[current_cons], COND); video.cursor_blink((unsigned int)&vc[current_cons]); } } void unblank_screen(struct vconsole *vc) { if(!(vc->flags & CONSOLE_BLANKED)) { return; } video.restore_screen(vc); vc->flags &= ~CONSOLE_BLANKED; video.show_cursor(vc, ON); } void vconsole_start(struct tty *tty) { struct vconsole *vc; vc = (struct vconsole *)tty->driver_data; if(!vc->scrlock) { return; } vc->led_status &= ~SCRLBIT; vc->scrlock = 0; set_leds(vc->led_status); } void vconsole_stop(struct tty *tty) { struct vconsole *vc; vc = (struct vconsole *)tty->driver_data; if(vc->scrlock) { return; } vc->led_status |= SCRLBIT; vc->scrlock = 1; set_leds(vc->led_status); } void vconsole_beep(void) { struct callout_req creq; pit_beep_on(); creq.fn = pit_beep_off; creq.arg = 0; add_callout(&creq, HZ / 8); } void vconsole_deltab(struct tty *tty) { int col, n; unsigned char count; struct vconsole *vc; struct cblock *cb; unsigned char ch; vc = (struct vconsole *)tty->driver_data; cb = tty->cooked_q.head; col = count = 0; while(cb) { for(n = 0; n < cb->end_off; n++) { if(n >= cb->start_off) { ch = cb->data[n]; if(ch == '\t') { while(!vc->tty->tab_stop[++col]); } else { col++; if(ISCNTRL(ch) && !ISSPACE(ch) && tty->termios.c_lflag & ECHOCTL) { col++; } } col %= vc->columns; } } cb = cb->next; } count = vc->x - col; while(count--) { tty_queue_putchar(tty, &tty->write_q, '\b'); } } void console_flush_log_buf(char *buffer, unsigned int count) { char *b; struct tty *tty; if(!(tty = get_tty(_syscondev))) { _syscondev = MKDEV(VCONSOLES_MAJOR, 0); tty = get_tty(_syscondev); } b = buffer; while(count) { if(tty_queue_putchar(tty, &tty->write_q, *b) < 0) { tty->output(tty); continue; } count--; b++; } tty->output(tty); } void console_init(void) { int n; struct tty *tty; if(video.flags & VPF_VGA) { printk("console 0x%04X-0x%04X - %s (%d virtual consoles)\n", video.port, video.port + 1, video.signature, NR_VCONSOLES); } if(video.flags & VPF_VESAFB) { printk("console - color frame buffer, screen=%dx%d, font=%dx%d\n", video.columns, video.lines, video.fb_char_width, video.fb_char_height); printk("\t\t\t\t(%d virtual consoles)\n", NR_VCONSOLES); } for(n = 1; n <= NR_VCONSOLES; n++) { if(!register_tty(MKDEV(VCONSOLES_MAJOR, n))) { tty = get_tty(MKDEV(VCONSOLES_MAJOR, n)); tty->driver_data = (void *)&vc[n]; tty->stop = vconsole_stop; tty->start = vconsole_start; tty->deltab = vconsole_deltab; tty->reset = vconsole_reset; tty->input = do_cook; tty->output = vconsole_write; vc[n].tty = tty; if(video.flags & VPF_VGA) { vc[n].screen = (short int *)kmalloc(); } if(video.flags & VPF_VESAFB) { vc[n].screen = vc_screen[n]; } vc[n].vidmem = NULL; memset_w(vc[n].screen, BLANK_MEM, SCREEN_SIZE); vconsole_reset(tty); } } current_cons = 1; video.show_cursor(&vc[current_cons], ON); vc[current_cons].vidmem = (unsigned char *)video.address; vc[current_cons].flags |= CONSOLE_HAS_FOCUS; if(video.flags & VPF_VGA) { memcpy_w(vc[current_cons].screen, video.address, SCREEN_SIZE); } video.get_curpos(&vc[current_cons]); video.update_curpos(&vc[current_cons]); video.buf_y = vc[current_cons].y; video.buf_top = 0; SET_MINOR(console_device.minors, 0); SET_MINOR(console_device.minors, 1); for(n = 0; n <= NR_VCONSOLES; n++) { SET_MINOR(tty_device.minors, n); } register_device(CHR_DEV, &console_device); register_device(CHR_DEV, &tty_device); if(is_vconsole(_syscondev)) { register_console(console_flush_log_buf); } }
FullOfBytes/Fiwix
fs/namei.c
/* * fiwix/fs/namei.c * * Copyright 2018-2021, <NAME>. All rights reserved. * Distributed under the terms of the Fiwix License. */ #include <fiwix/types.h> #include <fiwix/sleep.h> #include <fiwix/sched.h> #include <fiwix/fs.h> #include <fiwix/filesystems.h> #include <fiwix/stat.h> #include <fiwix/mm.h> #include <fiwix/mman.h> #include <fiwix/errno.h> #include <fiwix/stdio.h> #include <fiwix/string.h> static int namei_lookup(char *name, struct inode *dir, struct inode **i_res) { if(dir->fsop && dir->fsop->lookup) { return dir->fsop->lookup(name, dir, i_res); } return -EACCES; } static int do_namei(char *path, struct inode *dir, struct inode **i_res, struct inode **d_res, int follow_links) { char *name, *ptr_name; struct inode *i; struct superblock *sb; int errno; *i_res = dir; for(;;) { while(*path == '/') { path++; } if(*path == NULL) { return 0; } /* extracts the next component of the path */ if(!(name = (char *)kmalloc())) { return -ENOMEM; } ptr_name = name; while(*path != NULL && *path != '/') { if(ptr_name > name + NAME_MAX - 1) { break; } *ptr_name++ = *path++; } *ptr_name = NULL; /* * If the inode is the root of a file system, then return the * inode on which the file system was mounted. */ if(name[0] == '.' && name[1] == '.' && name[2] == NULL) { if(dir == dir->sb->root) { sb = dir->sb; iput(dir); dir = sb->dir; dir->count++; } } if((errno = check_permission(TO_EXEC, dir))) { break; } dir->count++; if((errno = namei_lookup(name, dir, &i))) { break; } kfree((unsigned int)name); if(*path == '/') { if(!S_ISDIR(i->i_mode) && !S_ISLNK(i->i_mode)) { iput(dir); iput(i); return -ENOTDIR; } if(S_ISLNK(i->i_mode)) { if(follow_links) { if(i->fsop && i->fsop->followlink) { if((errno = i->fsop->followlink(dir, i, &i))) { iput(dir); return errno; } } } else { iput(dir); iput(i); return -ENOTDIR; } } } else { if((i->fsop && i->fsop->followlink) && follow_links) { if((errno = i->fsop->followlink(dir, i, &i))) { iput(dir); return errno; } } } if(d_res) { if(*d_res) { iput(*d_res); } *d_res = dir; } else { iput(dir); } dir = i; *i_res = i; } kfree((unsigned int)name); if(d_res) { if(*d_res) { iput(*d_res); } /* * If that was the last component of the path, * then return the directory. */ if(*path == NULL) { *d_res = dir; dir->count++; } else { /* that's an non-existent directory */ *d_res = NULL; errno = -ENOTDIR; } iput(dir); *i_res = NULL; } else { iput(dir); } return errno; } int parse_namei(char *path, struct inode *base_dir, struct inode **i_res, struct inode **d_res, int follow_links) { struct inode *dir; int errno; if(!path) { return -EFAULT; } if(*path == NULL) { return -ENOENT; } if(!(dir = base_dir)) { dir = current->pwd; } /* it is definitely an absolute path */ if(path[0] == '/') { dir = current->root; } dir->count++; errno = do_namei(path, dir, i_res, d_res, follow_links); return errno; } /* * namei() returns: * i_res -> the inode of the last component of the path, or NULL. * d_res -> the inode of the directory where i_res resides, or NULL. */ int namei(char *path, struct inode **i_res, struct inode **d_res, int follow_links) { *i_res = NULL; if(d_res) { *d_res = NULL; } return parse_namei(path, NULL, i_res, d_res, follow_links); }
yixiangLuo/Liquid_Crystal
bingham.h
#ifndef BINGHAM_H #define BINGHAM_H #define PI 3.14159265359 /* the dividing number, which is denoted as d in the paper */ #define Divide (-30) /* total number of 2D interpolation nodes along x(and y) axis, in calculating Z, Z(x1^2) and Z(x2^2) */ #define InterpNodesNumAxis_2D_Z 1201 /* total number of 2D interpolation nodes along x(and y) axis, in calculating <x1^2>, <x2^2>, <x1^2*x2^2>, <x1^4> and <x2^4> */ #define InterpNodesNumAxis_2D_Q 301 /* grid size for 2D interpolation, in calculating Z, Z(x1^2) and Z(x2^2) */ #define AreaSpacing_Z 0.025 /* grid size for 2D interpolation, in calculating <x1^2>, <x2^2>, <x1^2*x2^2>, <x1^4> and <x2^4>. */ #define AreaSpacing_Q 0.1 /* total number of 1D interpolation nodes, in calculating the derivatives of g in case 2.2 in the paper. */ #define InterpNodesNumAxis_1D 30001 /* grid size for 1D interpolation, in calculating the derivatives of g in case 2.2 in the paper. */ #define LinearSpacing 0.001 /* Difine the data structure for storing the interpolation data. */ typedef struct binghamDataSpace{ double** binghamVal_Z; double** dB1Bingham_Z; double** dB2Bingham_Z; double** binghamVal_Z_x12; double** dB1Bingham_Z_x12; double** dB2Bingham_Z_x12; double** binghamVal_Q_x14; double** dB1Bingham_Q_x14; double** dB2Bingham_Q_x14; double** binghamVal_Q_x12x22; double** dB1Bingham_Q_x12x22; double** dB2Bingham_Q_x12x22; double** finite1D_x0; double** finite1D_x2; double** finite1D_x4; } binghamDataSpace; /* Difine the data structure of the result. */ typedef struct Moments{ double Z; double Z_x12; double Z_x22; double Q_x12; double Q_x22; double Q_x12x22; double Q_x14; double Q_x24; } Moments; /* 2D interpolation function */ double hermiteInterpolate(double areaSpacing, double x1, double x2, double y1, double y2, double f11, double f12, double f21, double f22, double f11dx, double f12dx, double f21dx, double f22dx, double f11dy, double f12dy, double f21dy, double f22dy, double x, double y); /* 1D interpolation function */ double calcDerivative(double x, int order, double** finite1D); /* sort the input array b in a increasing order and record its original order */ void sort(double (*array)[3], int rowNum); /* release the heap memory allocated for the data structure. */ void binghamDataFree(binghamDataSpace* binghamDataPointer); /* allocate heap memory for the data structure and read in the data from binghamData.bi */ binghamDataSpace* initiateBingham(); /* function for calculating the moments of Bingham distribution */ Moments bingham(double* b, binghamDataSpace* binghamDataPointer); #endif
yixiangLuo/Liquid_Crystal
header.h
<filename>header.h #ifndef ENERGYFUNCTIONAL #define ENERGYFUNCTIONAL #define PI 3.14159265359 #define Alpha1 22.0 //11~-2 16~-6 22~-12 #define Alpha2 0.04 #define Eta 50.0 #define S 0.48 //强锚定边界条件的特征值参数(0,1) #define PointNumInRadius 32 #define PointNumInTheta 32 #define PointNumInPhi 32 #define PointTotalNum (PointNumInRadius*PointNumInTheta*PointNumInPhi) //#define FreeVarsUnitNum (PointNumInRadius*PointNumInTheta) //#define FreeVarsTotalNum (5*FreeVarsUnitNum) #define RadiusSlice 2 #define ThetaSlice 2 #define PhiSlice 2 #define SplitCorePoint 0.5 //0.01-0.5 #define Gaussian_index(N) ((N) <= (64) ? (N-2) : (63)) #define Point_index(i,j,k) ((i)*PointNumInTheta*PointNumInPhi+(j)*PointNumInPhi+(k)) #define max2(a, b) ((a) >= (b) ? (a) : (b)) #define max3(a, b, c) max2(max2((a), (b)), (c)) typedef struct energySpace{ double energy; //能量泛函的值 //double* freeVars; //自由变量,由此生成B,数量FreeVarsUnitNum视限制条件而定,如旋转对称/粘接球体,具体见initEnergySpace double* Bdiag_Angle_Elements; //自变量,5*PointTotalNum个线性排开,前两个为B的两个特征值,后三个为将B对角化的旋转矩阵的欧拉角 double* Qdiag_elements; //Q的2个特征值,2*PointTotalNum个线性排开 double* Q_elements; //Q的5个元素,5*PointTotalNum个线性排开 double* Z_elements; //标准化常数Z double** dZ_dBdiag; //Z对B的特征值的偏导数,二维数组 double** dQdiag_dBdiag; //Q的特征值对B的特征值的偏导数,4行分别为dQ1_dB1, dQ1_dB2, dQ2_dB1, dQ2_dB2, PointTotalNum列 double** dQ_dBdiagAngle; //Q对B的偏导数,25列,每5列是Qi对Bi(特征值or欧拉角,共5个,Qi的指标先变化)的偏导数 double* dEnergy_dB; //能量泛函对5个自变量的偏导数,5*PointTotalNum个线性排开 //double* dEnergy_freeVars; //对自由变量的偏导数 double* pointInRadius; //r方向上的节点 double* pointInTheta; //theta方向上的节点 double* pointInPhi; //phi方向上的节点 double** pointsInBall; //单位球中的数值积分节点,3行,分别表示x,y,z double** pointsInSphere; //单位球面上的数值积分节点,3行,分别表示x,y,z double* ballInteCor; //单位球中的数值积分系数,PointTotalNum个 double* sphereInteCor; //单位球面上的数值积分系数,PointNumInTheta*PointNumInPhi个 //多项式方法 double** gradMatrix_radius; //在r方向由q点处值求q点处对r的偏导数值的矩阵,列为与点值相乘的系数,行为某点处的偏导数 double** gradMatrix_theta; double** gradMatrix_phi; double* sideValVector; //利用r方向上点值计算球面上函数值的系数向量,PointNumInRadius个 //存储计算中间值 double** dQ_drtp; double** dEnergy_dQdrtp; double** dEnergy_dQ; } energySpace; #endif
yixiangLuo/Liquid_Crystal
calcEnergy.c
#include "calcEnergy.h" #include <stdlib.h> #include <stdio.h> #include <math.h> #include <time.h> #include "header.h" #include "bingham.h" #include "initEnergySpace.h" extern energySpace* energyDataPointer; extern binghamDataSpace* binghamDataPointer; extern mpi_comm_data* mpi_comm_space; extern clock_t comm_start, comm_end, comm_time; mpi_comm_data* mpi_init_space(){ mpi_comm_data* mpi_comm_space = (mpi_comm_data*) malloc(sizeof(mpi_comm_data)); mpi_comm_space->mpi_comm_groups = (MPI_Comm*) malloc(3*sizeof(MPI_Comm)); mpi_comm_space->local_total_num = PointTotalNum/(RadiusSlice*ThetaSlice*PhiSlice); mpi_comm_space->mpi_msg_send = linearSpace_MPI(5*mpi_comm_space->local_total_num, mpi_comm_space); mpi_comm_space->mpi_msg_rec = linearSpace_MPI(max3(RadiusSlice,ThetaSlice,PhiSlice)*5*mpi_comm_space->local_total_num, mpi_comm_space); int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); int color_radius = rank%(ThetaSlice*PhiSlice); int color_theta = rank/(ThetaSlice*PhiSlice)*size+rank%PhiSlice; int color_phi = rank/(ThetaSlice*PhiSlice)*size+rank%(ThetaSlice*PhiSlice)/PhiSlice; MPI_Comm_split(MPI_COMM_WORLD, color_radius, rank, &mpi_comm_space->mpi_comm_groups[0]); MPI_Comm_split(MPI_COMM_WORLD, color_theta, rank, &mpi_comm_space->mpi_comm_groups[1]); MPI_Comm_split(MPI_COMM_WORLD, color_phi, rank, &mpi_comm_space->mpi_comm_groups[2]); return mpi_comm_space; } void mpi_free_space(mpi_comm_data* mpi_comm_space){ if(!mpi_comm_space) return; MPI_Comm_free(&mpi_comm_space->mpi_comm_groups[0]); MPI_Comm_free(&mpi_comm_space->mpi_comm_groups[1]); MPI_Comm_free(&mpi_comm_space->mpi_comm_groups[2]); free((void*) mpi_comm_space->mpi_comm_groups); free((void*) mpi_comm_space->mpi_msg_send); free((void*) mpi_comm_space->mpi_msg_rec); free((void *)mpi_comm_space); } double* linearSpace_MPI(int size, mpi_comm_data* mpi_comm_space){ double* dataSpace = (double*) malloc(size*sizeof(double)); if(dataSpace==NULL){ mpi_free_space(mpi_comm_space); printf("fail to allocate temp space: menmory not enough!\n"); exit(1); } return dataSpace; } void exchange_vals(int rank, double** src, double** des, mpi_comm_data* mpi_comm_space, int same){ int i, n, m, l, q_index, n_index, m_index, l_index, block_index; int radius_l = Radius_Low(rank); int radius_u = Radius_Up(rank); int theta_l = Theta_Low(rank); int theta_u = Theta_Up(rank); int phi_l = Phi_Low(rank); int phi_u = Phi_Up(rank); int local_total_num = mpi_comm_space->local_total_num; double* dEnergy_dQdr_msg = (double*) malloc(5*local_total_num*sizeof(double)); double* dEnergy_dQdr_rev = (double*) malloc(RadiusSlice*5*local_total_num*sizeof(double)); for(i=0;i<3;i++){ if(same==0 || (same==1 && i==0)) for(n=radius_l; n<radius_u; n++){ n_index = (n-radius_l)*(theta_u-theta_l)*(phi_u-phi_l); for(m=theta_l; m<theta_u; m++){ m_index = (m-theta_l)*(phi_u-phi_l); for(l=phi_l; l<phi_u; l++){ l_index = l-phi_l; for(q_index=0; q_index<5; q_index++){ mpi_comm_space->mpi_msg_send[n_index+m_index+l_index+q_index*local_total_num] = src[i][Point_index(n,m,l)+q_index*PointTotalNum]; } } } } comm_start = clock(); MPI_Allgather(mpi_comm_space->mpi_msg_send, 5*local_total_num, MPI_DOUBLE, mpi_comm_space->mpi_msg_rec, 5*local_total_num, MPI_DOUBLE, mpi_comm_space->mpi_comm_groups[i]); comm_end = clock(); comm_time += comm_end-comm_start; for(n=(i==0?0:radius_l); n<(i==0?PointNumInRadius:radius_u); n++){ n_index = n%(radius_u-radius_l)*(theta_u-theta_l)*(phi_u-phi_l); if(i==0) block_index = n/(radius_u-radius_l); for(m=(i==1?0:theta_l); m<(i==1?PointNumInTheta:theta_u); m++){ m_index = m%(theta_u-theta_l)*(phi_u-phi_l); if(i==1) block_index = m/(theta_u-theta_l); for(l=(i==2?0:phi_l); l<(i==2?PointNumInPhi:phi_u); l++){ l_index = l%(phi_u-phi_l); if(i==2) block_index = l/(phi_u-phi_l); for(q_index=0; q_index<5; q_index++){ des[i][Point_index(n,m,l)+q_index*PointTotalNum] = mpi_comm_space->mpi_msg_rec[block_index*5*local_total_num+n_index+m_index+l_index+q_index*local_total_num]; } } } } } } /*void makeB(){ int i, j, k, q_index; int indexBasis_B, indexBasis_Var; //径向对称 / *for(i=0; i<PointNumInRadius; i++){ for(q_index=0; q_index<2; q_index++){ for(j=0; j<PointNumInTheta; j++){ indexBasis_B=i*PointNumInTheta*PointNumInPhi+j*PointNumInPhi+q_index*PointTotalNum; for(k=0; k<PointNumInPhi; k++){ energyDataPointer->Bdiag_Angle_Elements[indexBasis_B+k]=energyDataPointer->freeVars[i]; } } } }* / //旋转对称 for(i=0; i<PointNumInRadius; i++){ for(q_index=0; q_index<4; q_index++){ indexBasis_Var=i*PointNumInTheta+q_index*FreeVarsUnitNum; for(j=0; j<PointNumInTheta; j++){ //if(fabs(energyDataPointer->pointInRadius[i]*cos(energyDataPointer->pointInTheta[j]))<SplitCorePoint) continue; //split core 初次求解,限定中部横向,配合初值使用 indexBasis_B=i*PointNumInTheta*PointNumInPhi+j*PointNumInPhi+q_index*PointTotalNum; for(k=0; k<PointNumInPhi; k++){ energyDataPointer->Bdiag_Angle_Elements[indexBasis_B+k]=energyDataPointer->freeVars[indexBasis_Var+j]; } } } //q_index=4 indexBasis_Var=i*PointNumInTheta+4*FreeVarsUnitNum; for(j=0; j<PointNumInTheta; j++){ //if(fabs(energyDataPointer->pointInRadius[i]*cos(energyDataPointer->pointInTheta[j]))<SplitCorePoint) continue; //split core 初次求解,限定中部横向,配合初值使用 indexBasis_B=i*PointNumInTheta*PointNumInPhi+j*PointNumInPhi+4*PointTotalNum; for(k=0; k<PointNumInPhi; k++){ energyDataPointer->Bdiag_Angle_Elements[indexBasis_B+k]=energyDataPointer->freeVars[indexBasis_Var+j]-energyDataPointer->pointInPhi[k]; } } } }*/ /*void makeFreeVars(){ int i, j, k, q_index; int indexBasis_B, indexBasis_Var; //径向对称 / *for(i=0; i<PointNumInRadius; i++){ energyDataPointer->freeVars[i]=energyDataPointer->Bdiag_Angle_Elements[i*PointNumInTheta*PointNumInPhi]; }* / //旋转对称 for(i=0; i<PointNumInRadius; i++){ for(q_index=0; q_index<4; q_index++){ indexBasis_Var=i*PointNumInTheta+q_index*FreeVarsUnitNum; for(j=0; j<PointNumInTheta; j++){ indexBasis_B=i*PointNumInTheta*PointNumInPhi+j*PointNumInPhi+q_index*PointTotalNum; energyDataPointer->freeVars[indexBasis_Var+j]=energyDataPointer->Bdiag_Angle_Elements[indexBasis_B]; } } //q_index=4 indexBasis_Var=i*PointNumInTheta+4*FreeVarsUnitNum; for(j=0; j<PointNumInTheta; j++){ indexBasis_B=i*PointNumInTheta*PointNumInPhi+j*PointNumInPhi+4*PointTotalNum; energyDataPointer->freeVars[indexBasis_Var+j]=energyDataPointer->Bdiag_Angle_Elements[indexBasis_B]+energyDataPointer->pointInPhi[0]; } } }*/ /*void transVarsBack(){ int i, j, k, q_index; int indexBasis_B, indexBasis_Var; for(i=0; i<FreeVarsTotalNum; i++){ energyDataPointer->dEnergy_freeVars[i]=0; } //径向对称 / *for(i=0; i<PointNumInRadius; i++){ for(q_index=0; q_index<2; q_index++){ for(j=0; j<PointNumInTheta; j++){ indexBasis_B=i*PointNumInTheta*PointNumInPhi+j*PointNumInPhi+q_index*PointTotalNum; for(k=0; k<PointNumInPhi; k++){ energyDataPointer->dEnergy_freeVars[i]+=energyDataPointer->dEnergy_dB[indexBasis_B+k]; } } } }* / //旋转对称 for(i=0; i<PointNumInRadius; i++){ for(q_index=0; q_index<5; q_index++){ indexBasis_Var=i*PointNumInTheta+q_index*FreeVarsUnitNum; for(j=0; j<PointNumInTheta; j++){ //if(fabs(energyDataPointer->pointInRadius[i]*cos(energyDataPointer->pointInTheta[j]))<SplitCorePoint) continue; //split core 初次求解,限定中部横向,配合初值使用 indexBasis_B=i*PointNumInTheta*PointNumInPhi+j*PointNumInPhi+q_index*PointTotalNum; for(k=0; k<PointNumInPhi; k++){ energyDataPointer->dEnergy_freeVars[indexBasis_Var+j]+=energyDataPointer->dEnergy_dB[indexBasis_B+k]; } } } } }*/ double eval_energy(){ int rank; double energy=0; double *Q_elem[3]; Q_elem[0]=energyDataPointer->Q_elements; Q_elem[1]=energyDataPointer->Q_elements; Q_elem[2]=energyDataPointer->Q_elements; MPI_Comm_rank(MPI_COMM_WORLD, &rank); preCalculate(rank); exchange_vals(rank, Q_elem, Q_elem, mpi_comm_space, 1); calc_Fbulk(rank); calc_Felas(rank); calc_Fpena(rank); comm_start = clock(); MPI_Allreduce(&energyDataPointer->energy, &energy, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); comm_end = clock(); comm_time += comm_end-comm_start; return energy; } void preCalculate(int rank){ int i; int n, m, l, q_index; int radius_l = Radius_Low(rank); int radius_u = Radius_Up(rank); int theta_l = Theta_Low(rank); int theta_u = Theta_Up(rank); int phi_l = Phi_Low(rank); int phi_u = Phi_Up(rank); Moments M; double bingham_B[3]={0}; //计算Q的特征值、Z以及它们关于B的特征值的偏导数 for(n=radius_l; n<radius_u; n++){ for(m=theta_l; m<theta_u; m++){ for(l=phi_l; l<phi_u; l++){ i=Point_index(n,m,l); bingham_B[0]=energyDataPointer->Bdiag_Angle_Elements[i]; bingham_B[1]=energyDataPointer->Bdiag_Angle_Elements[PointTotalNum+i]; bingham_B[2]=-energyDataPointer->Bdiag_Angle_Elements[i]-energyDataPointer->Bdiag_Angle_Elements[PointTotalNum+i]; M = bingham(bingham_B, binghamDataPointer); energyDataPointer->Z_elements[i]=M.Z; energyDataPointer->dZ_dBdiag[0][i]=2*M.Z_x12+M.Z_x22-M.Z; energyDataPointer->dZ_dBdiag[1][i]=M.Z_x12+2*M.Z_x22-M.Z; energyDataPointer->Qdiag_elements[i]=M.Q_x12-1.0/3; energyDataPointer->Qdiag_elements[PointTotalNum+i]=M.Q_x22-1.0/3; energyDataPointer->dQdiag_dBdiag[0][i]=2*M.Q_x14+M.Q_x12x22-(2*M.Q_x12+M.Q_x22)*M.Q_x12; //dQ1_dB1 energyDataPointer->dQdiag_dBdiag[1][i]=M.Q_x14+2*M.Q_x12x22-(M.Q_x12+2*M.Q_x22)*M.Q_x12; //dQ1_dB2 energyDataPointer->dQdiag_dBdiag[2][i]=2*M.Q_x12x22+M.Q_x24-(2*M.Q_x12+M.Q_x22)*M.Q_x22; //dQ2_dB1 energyDataPointer->dQdiag_dBdiag[3][i]=M.Q_x12x22+2*M.Q_x24-(M.Q_x12+2*M.Q_x22)*M.Q_x22; //dQ2_dB2 calc_Q_dQdB(i); } } } energyDataPointer->energy=0; for(n=radius_l; n<radius_u; n++){ for(m=theta_l; m<theta_u; m++){ for(l=phi_l; l<phi_u; l++){ i=Point_index(n,m,l); for(q_index=0; q_index<5; q_index++){ energyDataPointer->dEnergy_dB[i+q_index*PointTotalNum]=0; } } } } } //通过B旋转矩阵的值和Q的特征值,计算Q的值及Q关于自变量B的偏导数的值 void calc_Q_dQdB(int i){ double alpha=energyDataPointer->Bdiag_Angle_Elements[2*PointTotalNum+i]; double beta=energyDataPointer->Bdiag_Angle_Elements[3*PointTotalNum+i]; double gamma=energyDataPointer->Bdiag_Angle_Elements[4*PointTotalNum+i]; double Q_diag[3]={energyDataPointer->Qdiag_elements[i], energyDataPointer->Qdiag_elements[PointTotalNum+i], -energyDataPointer->Qdiag_elements[i]-energyDataPointer->Qdiag_elements[PointTotalNum+i]}; double dQdiag_dB[2][3]={{energyDataPointer->dQdiag_dBdiag[0][i], energyDataPointer->dQdiag_dBdiag[2][i], -energyDataPointer->dQdiag_dBdiag[0][i]-energyDataPointer->dQdiag_dBdiag[2][i]}, {energyDataPointer->dQdiag_dBdiag[1][i], energyDataPointer->dQdiag_dBdiag[3][i], -energyDataPointer->dQdiag_dBdiag[1][i]-energyDataPointer->dQdiag_dBdiag[3][i]}}; double sin_alpha=sin(alpha), cos_alpha=cos(alpha); double sin_beta=sin(beta), cos_beta=cos(beta); double sin_gamma=sin(gamma), cos_gamma=cos(gamma); double euler[3][3]={ {cos_alpha*cos_gamma - cos_beta*sin_alpha*sin_gamma, cos_gamma*sin_alpha + cos_alpha*cos_beta*sin_gamma, sin_beta*sin_gamma}, {-(cos_beta*cos_gamma*sin_alpha) - cos_alpha*sin_gamma, cos_alpha*cos_beta*cos_gamma - sin_alpha*sin_gamma, cos_gamma*sin_beta}, {sin_alpha*sin_beta, -(cos_alpha*sin_beta), cos_beta}}; double euler_dAlpha[3][3]={ {-(cos_gamma*sin_alpha) - cos_alpha*cos_beta*sin_gamma,cos_alpha*cos_gamma - cos_beta*sin_alpha*sin_gamma,0}, {-(cos_alpha*cos_beta*cos_gamma) + sin_alpha*sin_gamma,-(cos_beta*cos_gamma*sin_alpha) - cos_alpha*sin_gamma,0}, {cos_alpha*sin_beta,sin_alpha*sin_beta,0}}; double euler_dBeta[3][3]={ {sin_alpha*sin_beta*sin_gamma,-(cos_alpha*sin_beta*sin_gamma),cos_beta*sin_gamma}, {cos_gamma*sin_alpha*sin_beta,-(cos_alpha*cos_gamma*sin_beta),cos_beta*cos_gamma}, {cos_beta*sin_alpha,-(cos_alpha*cos_beta),-sin_beta}}; double euler_dGamma[3][3]={ {-(cos_beta*cos_gamma*sin_alpha) - cos_alpha*sin_gamma,cos_alpha*cos_beta*cos_gamma - sin_alpha*sin_gamma,cos_gamma*sin_beta}, {-(cos_alpha*cos_gamma) + cos_beta*sin_alpha*sin_gamma,-(cos_gamma*sin_alpha) - cos_alpha*cos_beta*sin_gamma,-(sin_beta*sin_gamma)}, {0,0,0}}; int indexTans[2][5]={{0, 0, 0, 1, 1}, {0, 1, 2, 1, 2}}; int k, j; double val, val1, val2, val3; for(k=0; k<5; k++){ val1=0; val2=0; val3=0; for(j=0; j<3; j++){ val=euler[indexTans[0][k]][j]*euler[indexTans[1][k]][j]; val1+=val*Q_diag[j]; val2+=val*dQdiag_dB[0][j]; val3+=val*dQdiag_dB[1][j]; } energyDataPointer->Q_elements[k*PointTotalNum+i]=val1; energyDataPointer->dQ_dBdiagAngle[i][k]=val2; energyDataPointer->dQ_dBdiagAngle[i][5+k]=val3; } for(k=0; k<5; k++){ val1=0; val2=0; val3=0; for(j=0; j<3; j++){ val1+=euler[indexTans[0][k]][j]*Q_diag[j]*euler_dAlpha[indexTans[1][k]][j]+euler[indexTans[1][k]][j]*Q_diag[j]*euler_dAlpha[indexTans[0][k]][j]; val2+=euler[indexTans[0][k]][j]*Q_diag[j]*euler_dBeta[indexTans[1][k]][j]+euler[indexTans[1][k]][j]*Q_diag[j]*euler_dBeta[indexTans[0][k]][j]; val3+=euler[indexTans[0][k]][j]*Q_diag[j]*euler_dGamma[indexTans[1][k]][j]+euler[indexTans[1][k]][j]*Q_diag[j]*euler_dGamma[indexTans[0][k]][j]; } energyDataPointer->dQ_dBdiagAngle[i][2*5+k]=val1; energyDataPointer->dQ_dBdiagAngle[i][3*5+k]=val2; energyDataPointer->dQ_dBdiagAngle[i][4*5+k]=val3; } } void calc_Fbulk(int rank){ int i; int n, m, l; int radius_l = Radius_Low(rank); int radius_u = Radius_Up(rank); int theta_l = Theta_Low(rank); int theta_u = Theta_Up(rank); int phi_l = Phi_Low(rank); int phi_u = Phi_Up(rank); double energy=0; //Int[Q:B - Ln(Z)] = b1*q1 + b2*q2 + (b1 + b2)*(q1 + q2) - ln(Z) //泛函值 energy=0; for(n=radius_l; n<radius_u; n++){ for(m=theta_l; m<theta_u; m++){ for(l=phi_l; l<phi_u; l++){ i=Point_index(n,m,l); energy += energyDataPointer->ballInteCor[i]*(energyDataPointer->Bdiag_Angle_Elements[i]*energyDataPointer->Qdiag_elements[i] + energyDataPointer->Bdiag_Angle_Elements[PointTotalNum+i]*energyDataPointer->Qdiag_elements[PointTotalNum+i] + (energyDataPointer->Bdiag_Angle_Elements[i] + energyDataPointer->Bdiag_Angle_Elements[PointTotalNum+i]) * (energyDataPointer->Qdiag_elements[i] + energyDataPointer->Qdiag_elements[PointTotalNum+i]) - log(energyDataPointer->Z_elements[i])); } } } energyDataPointer->energy += energy; //对自变量的导数 for(n=radius_l; n<radius_u; n++){ for(m=theta_l; m<theta_u; m++){ for(l=phi_l; l<phi_u; l++){ i=Point_index(n,m,l); //dEnergy_dB1 energyDataPointer->dEnergy_dB[i] += energyDataPointer->ballInteCor[i]*( 2*energyDataPointer->Qdiag_elements[i] + energyDataPointer->Qdiag_elements[PointTotalNum+i] + (2*energyDataPointer->Bdiag_Angle_Elements[i] + energyDataPointer->Bdiag_Angle_Elements[PointTotalNum+i])*energyDataPointer->dQdiag_dBdiag[0][i] + (energyDataPointer->Bdiag_Angle_Elements[i] + 2*energyDataPointer->Bdiag_Angle_Elements[PointTotalNum+i])*energyDataPointer->dQdiag_dBdiag[2][i] - energyDataPointer->dZ_dBdiag[0][i]/energyDataPointer->Z_elements[i]); //dEnergy_dB2 energyDataPointer->dEnergy_dB[PointTotalNum+i] += energyDataPointer->ballInteCor[i]*( energyDataPointer->Qdiag_elements[i] + 2*energyDataPointer->Qdiag_elements[PointTotalNum+i] + (2*energyDataPointer->Bdiag_Angle_Elements[i] + energyDataPointer->Bdiag_Angle_Elements[PointTotalNum+i])*energyDataPointer->dQdiag_dBdiag[1][i] + (energyDataPointer->Bdiag_Angle_Elements[i] + 2*energyDataPointer->Bdiag_Angle_Elements[PointTotalNum+i])*energyDataPointer->dQdiag_dBdiag[3][i] - energyDataPointer->dZ_dBdiag[1][i]/energyDataPointer->Z_elements[i]); //其他为0 } } } //Int[|Q|^2] = q1^2 + q2^2 + (q1 + q2)^2 //泛函值 energy=0; for(n=radius_l; n<radius_u; n++){ for(m=theta_l; m<theta_u; m++){ for(l=phi_l; l<phi_u; l++){ i=Point_index(n,m,l); energy += energyDataPointer->ballInteCor[i]*2*(energyDataPointer->Qdiag_elements[i]*energyDataPointer->Qdiag_elements[i] + energyDataPointer->Qdiag_elements[i]*energyDataPointer->Qdiag_elements[PointTotalNum+i] + energyDataPointer->Qdiag_elements[PointTotalNum+i]*energyDataPointer->Qdiag_elements[PointTotalNum+i]); } } } energyDataPointer->energy += -Alpha1*0.5 * energy; //对自变量的导数 for(n=radius_l; n<radius_u; n++){ for(m=theta_l; m<theta_u; m++){ for(l=phi_l; l<phi_u; l++){ i=Point_index(n,m,l); //dEnergy_dB1 energyDataPointer->dEnergy_dB[i] += -Alpha1*0.5 * energyDataPointer->ballInteCor[i]*2*(energyDataPointer->Qdiag_elements[i]*(2*energyDataPointer->dQdiag_dBdiag[0][i] + energyDataPointer->dQdiag_dBdiag[2][i]) + energyDataPointer->Qdiag_elements[PointTotalNum+i]*(energyDataPointer->dQdiag_dBdiag[0][i] + 2*energyDataPointer->dQdiag_dBdiag[2][i])); //dEnergy_dB2 energyDataPointer->dEnergy_dB[PointTotalNum+i] += -Alpha1*0.5 * energyDataPointer->ballInteCor[i]*2*(energyDataPointer->Qdiag_elements[i]*(2*energyDataPointer->dQdiag_dBdiag[1][i] + energyDataPointer->dQdiag_dBdiag[3][i]) + energyDataPointer->Qdiag_elements[PointTotalNum+i]*(energyDataPointer->dQdiag_dBdiag[1][i] + 2*energyDataPointer->dQdiag_dBdiag[3][i])); //其他为0 } } } } void calc_Felas(int rank){ int i, j, k, n, m, l, q_index; int indexBasis; int radius_l = Radius_Low(rank); int radius_u = Radius_Up(rank); int theta_l = Theta_Low(rank); int theta_u = Theta_Up(rank); int phi_l = Phi_Low(rank); int phi_u = Phi_Up(rank); double count=0, energy=0; for(q_index=0; q_index<5; q_index++){ for(j=theta_l; j<theta_u; j++){ for(k=phi_l; k<phi_u; k++){ indexBasis=j*PointNumInPhi+k+q_index*PointTotalNum; for(l=radius_l; l<radius_u; l++){ count=0; for(i=0; i<PointNumInRadius; i++){ count+=energyDataPointer->gradMatrix_radius[l][i] * energyDataPointer->Q_elements[i*PointNumInTheta*PointNumInPhi+indexBasis]; } energyDataPointer->dQ_drtp[0][l*PointNumInTheta*PointNumInPhi+indexBasis]=count; } } } for(i=radius_l; i<radius_u; i++){ for(k=phi_l; k<phi_u; k++){ indexBasis=i*PointNumInTheta*PointNumInPhi+k+q_index*PointTotalNum; for(l=theta_l; l<theta_u; l++){ count=0; for(j=0; j<PointNumInTheta; j++){ count+=energyDataPointer->gradMatrix_theta[l][j] * energyDataPointer->Q_elements[j*PointNumInPhi+indexBasis]; } energyDataPointer->dQ_drtp[1][l*PointNumInPhi+indexBasis]=count; } } } for(i=radius_l; i<radius_u; i++){ for(j=theta_l; j<theta_u; j++){ indexBasis=i*PointNumInTheta*PointNumInPhi+j*PointNumInPhi+q_index*PointTotalNum; for(l=phi_l; l<phi_u; l++){ count=0; for(k=0; k<PointNumInPhi; k++){ count+=energyDataPointer->gradMatrix_phi[l][k] * energyDataPointer->Q_elements[k+indexBasis]; } energyDataPointer->dQ_drtp[2][l+indexBasis]=count; } } } } double dQ_dxyz[3][5]={0}; //行dx,dy,dz, 列q1,q2,...,q5 double x, y, z; double norm, norm_2, semiNorm, semiNorm_2; double cordTrans[3][3]; energy=0; for(n=radius_l; n<radius_u; n++){ for(m=theta_l; m<theta_u; m++){ for(l=phi_l; l<phi_u; l++){ i=Point_index(n,m,l); //将“对rtp的导数”转化为“对xyz的导数”的准备 x=energyDataPointer->pointsInBall[0][i]; y=energyDataPointer->pointsInBall[1][i]; z=energyDataPointer->pointsInBall[2][i]; semiNorm_2=x*x+y*y; semiNorm=sqrt(semiNorm_2); norm_2=semiNorm_2+z*z; norm=sqrt(norm_2); cordTrans[0][0]=x/norm; cordTrans[0][1]=x*z/semiNorm/norm_2; cordTrans[0][2]=-y/semiNorm_2; cordTrans[1][0]=y/norm; cordTrans[1][1]=y*z/semiNorm/norm_2; cordTrans[1][2]=x/semiNorm_2; cordTrans[2][0]=z/norm; cordTrans[2][1]=-semiNorm/norm_2; cordTrans[2][2]=0; //算出i点处q1-q5的对xyz的偏导数值 for(q_index=0; q_index<5; q_index++){ for(j=0; j<3; j++){ dQ_dxyz[j][q_index]=cordTrans[j][0]*energyDataPointer->dQ_drtp[0][i+q_index*PointTotalNum] + cordTrans[j][1]*energyDataPointer->dQ_drtp[1][i+q_index*PointTotalNum] + cordTrans[j][2]*energyDataPointer->dQ_drtp[2][i+q_index*PointTotalNum]; } } //计算泛函值 count=0; for(q_index=0; q_index<5; q_index++){ count+=dQ_dxyz[0][q_index]*dQ_dxyz[0][q_index]+dQ_dxyz[1][q_index]*dQ_dxyz[1][q_index]+dQ_dxyz[2][q_index]*dQ_dxyz[2][q_index]; } energy += energyDataPointer->ballInteCor[i]*(count + dQ_dxyz[0][0]*dQ_dxyz[0][3]+dQ_dxyz[1][0]*dQ_dxyz[1][3]+dQ_dxyz[2][0]*dQ_dxyz[2][3]); //计算dEnergy_dQdrtp for(q_index=1; q_index<5; q_index++){ //q2, q3, q5 if(q_index==3) continue; for(j=0; j<3; j++){ energyDataPointer->dEnergy_dQdrtp[j][i+q_index*PointTotalNum]=Alpha2*energyDataPointer->ballInteCor[i]*2*(cordTrans[0][j]*dQ_dxyz[0][q_index] + cordTrans[1][j]*dQ_dxyz[1][q_index] + cordTrans[2][j]*dQ_dxyz[2][q_index]); } } for(j=0; j<3; j++){ //q1 energyDataPointer->dEnergy_dQdrtp[j][i]=Alpha2*energyDataPointer->ballInteCor[i]*(cordTrans[0][j]*(2*dQ_dxyz[0][0]+dQ_dxyz[0][3]) + cordTrans[1][j]*(2*dQ_dxyz[1][0]+dQ_dxyz[1][3]) + cordTrans[2][j]*(2*dQ_dxyz[2][0]+dQ_dxyz[2][3])); } for(j=0; j<3; j++){ //q4 energyDataPointer->dEnergy_dQdrtp[j][i+3*PointTotalNum]=Alpha2*energyDataPointer->ballInteCor[i]*(cordTrans[0][j]*(2*dQ_dxyz[0][3]+dQ_dxyz[0][0]) + cordTrans[1][j]*(2*dQ_dxyz[1][3]+dQ_dxyz[1][0]) + cordTrans[2][j]*(2*dQ_dxyz[2][3]+dQ_dxyz[2][0])); } } } } energyDataPointer->energy += Alpha2*energy; // mpi传输dEnergy_dQdrtp exchange_vals(rank, energyDataPointer->dEnergy_dQdrtp, energyDataPointer->dEnergy_dQdrtp, mpi_comm_space, 0); /* int n_index, m_index, l_index, block_index; int local_total_num = (radius_u-radius_l)*(theta_u-theta_l)*(phi_u-phi_l); //radius组 double* dEnergy_dQdr_msg = (double*) malloc(5*local_total_num*sizeof(double)); double* dEnergy_dQdr_rev = (double*) malloc(RadiusSlice*5*local_total_num*sizeof(double)); for(n=radius_l; n<radius_u; n++){ n_index = (n-radius_l)*(theta_u-theta_l)*(phi_u-phi_l); for(m=theta_l; m<theta_u; m++){ m_index = (m-theta_l)*(phi_u-phi_l); for(l=phi_l; l<phi_u; l++){ l_index = l-phi_l; for(q_index=0; q_index<5; q_index++){ dEnergy_dQdr_msg[n_index+m_index+l_index+q_index*local_total_num] = energyDataPointer->dEnergy_dQdrtp[0][Point_index(n,m,l)+q_index*PointTotalNum]; } } } } MPI_Allgather(dEnergy_dQdr_msg, 5*local_total_num, MPI_DOUBLE, dEnergy_dQdr_rev, 5*local_total_num, MPI_DOUBLE, mpi_radius_group); for(n=0; n<PointNumInRadius; n++){ n_index = n%(radius_u-radius_l)*(theta_u-theta_l)*(phi_u-phi_l); block_index = n/(radius_u-radius_l); for(m=theta_l; m<theta_u; m++){ m_index = (m-theta_l)*(phi_u-phi_l); for(l=phi_l; l<phi_u; l++){ l_index = l-phi_l; for(q_index=0; q_index<5; q_index++){ energyDataPointer->dEnergy_dQdrtp[0][Point_index(n,m,l)+q_index*PointTotalNum] = dEnergy_dQdr_rev[block_index*5*local_total_num+n_index+m_index+l_index+q_index*local_total_num]; } } } } free((void *)dEnergy_dQdr_msg); free((void *)dEnergy_dQdr_rev); //theta组 double* dEnergy_dQdt_msg = (double*) malloc(5*local_total_num*sizeof(double)); double* dEnergy_dQdt_rev = (double*) malloc(ThetaSlice*5*local_total_num*sizeof(double)); for(n=radius_l; n<radius_u; n++){ n_index = (n-radius_l)*(theta_u-theta_l)*(phi_u-phi_l); for(m=theta_l; m<theta_u; m++){ m_index = (m-theta_l)*(phi_u-phi_l); for(l=phi_l; l<phi_u; l++){ l_index = l-phi_l; for(q_index=0; q_index<5; q_index++){ dEnergy_dQdt_msg[n_index+m_index+l_index+q_index*local_total_num] = energyDataPointer->dEnergy_dQdrtp[1][Point_index(n,m,l)+q_index*PointTotalNum]; } } } } MPI_Allgather(dEnergy_dQdt_msg, 5*local_total_num, MPI_DOUBLE, dEnergy_dQdt_rev, 5*local_total_num, MPI_DOUBLE, mpi_theta_group); for(m=0; m<PointNumInTheta; m++){ m_index = m%(theta_u-theta_l)*(phi_u-phi_l); block_index = m/(theta_u-theta_l); for(n=radius_l; n<radius_u; n++){ n_index = (n-radius_l)*(theta_u-theta_l)*(phi_u-phi_l); for(l=phi_l; l<phi_u; l++){ l_index = l-phi_l; for(q_index=0; q_index<5; q_index++){ energyDataPointer->dEnergy_dQdrtp[1][Point_index(n,m,l)+q_index*PointTotalNum] = dEnergy_dQdt_rev[block_index*5*local_total_num+n_index+m_index+l_index+q_index*local_total_num]; } } } } free((void *)dEnergy_dQdt_msg); free((void *)dEnergy_dQdt_rev); //phi组 double* dEnergy_dQdp_msg = (double*) malloc(5*local_total_num*sizeof(double)); double* dEnergy_dQdp_rev = (double*) malloc(PhiSlice*5*local_total_num*sizeof(double)); for(n=radius_l; n<radius_u; n++){ n_index = (n-radius_l)*(theta_u-theta_l)*(phi_u-phi_l); for(m=theta_l; m<theta_u; m++){ m_index = (m-theta_l)*(phi_u-phi_l); for(l=phi_l; l<phi_u; l++){ l_index = l-phi_l; for(q_index=0; q_index<5; q_index++){ dEnergy_dQdp_msg[n_index+m_index+l_index+q_index*local_total_num] = energyDataPointer->dEnergy_dQdrtp[2][Point_index(n,m,l)+q_index*PointTotalNum]; } } } } MPI_Allgather(dEnergy_dQdp_msg, 5*local_total_num, MPI_DOUBLE, dEnergy_dQdp_rev, 5*local_total_num, MPI_DOUBLE, mpi_phi_group); for(l=0; l<PointNumInPhi; l++){ l_index = l%(phi_u-phi_l); block_index = l/(phi_u-phi_l); for(n=radius_l; n<radius_u; n++){ n_index = (n-radius_l)*(theta_u-theta_l)*(phi_u-phi_l); for(m=theta_l; m<theta_u; m++){ m_index = (m-theta_l)*(phi_u-phi_l); for(q_index=0; q_index<5; q_index++){ energyDataPointer->dEnergy_dQdrtp[2][Point_index(n,m,l)+q_index*PointTotalNum] = dEnergy_dQdp_rev[block_index*5*local_total_num+n_index+m_index+l_index+q_index*local_total_num]; } } } } free((void *)dEnergy_dQdp_msg); free((void *)dEnergy_dQdp_rev); */ //继续计算偏导数 for(q_index=0; q_index<5; q_index++){ for(i=radius_l; i<radius_u; i++){ for(j=theta_l; j<theta_u; j++){ for(k=phi_l; k<phi_u; k++){ count=0; for(l=0; l<PointNumInRadius; l++){ count+=energyDataPointer->gradMatrix_radius[l][i] * energyDataPointer->dEnergy_dQdrtp[0][Point_index(l,j,k)+q_index*PointTotalNum]; } for(l=0; l<PointNumInTheta; l++){ count+=energyDataPointer->gradMatrix_theta[l][j] * energyDataPointer->dEnergy_dQdrtp[1][Point_index(i,l,k)+q_index*PointTotalNum]; } for(l=0; l<PointNumInPhi; l++){ count+=energyDataPointer->gradMatrix_phi[l][k] * energyDataPointer->dEnergy_dQdrtp[2][Point_index(i,j,l)+q_index*PointTotalNum]; } energyDataPointer->dEnergy_dQ[Point_index(i,j,k)][q_index]=count; } } } } double* pointer1; double* pointer2; for(n=radius_l; n<radius_u; n++){ for(m=theta_l; m<theta_u; m++){ for(l=phi_l; l<phi_u; l++){ i=Point_index(n,m,l); pointer1=energyDataPointer->dQ_dBdiagAngle[i]; for(j=0; j<5; j++){ pointer2=energyDataPointer->dEnergy_dQ[i]; count=0; for(k=0; k<5; k++){ count+=(*pointer1)*(*pointer2); pointer1++; pointer2++; } energyDataPointer->dEnergy_dB[j*PointTotalNum+i]+=count; } } } } pointer1=NULL; pointer2=NULL; } void calc_Fpena(int rank){ int i, j, k, n, m, l, q_index; int radius_l = Radius_Low(rank); int radius_u = Radius_Up(rank); int theta_l = Theta_Low(rank); int theta_u = Theta_Up(rank); int phi_l = Phi_Low(rank); int phi_u = Phi_Up(rank); int indexBasis, index; double row1, row2, row3; double x, y, z; double q[5]={0}; double q_std[5]={0}; double p[4]={0}; double dFpena_dq[5]={0}; double count=0, energy=0; energy=0; for(j=theta_l; j<theta_u; j++){ for(k=phi_l; k<phi_u; k++){ //计算球面上某点处的函数值(q1-q5) for(q_index=0; q_index<5; q_index++){ indexBasis=j*PointNumInPhi+k+q_index*PointTotalNum; count=0; for(i=0; i<PointNumInRadius; i++){ count+=energyDataPointer->sideValVector[i] * energyDataPointer->Q_elements[i*PointNumInTheta*PointNumInPhi+indexBasis]; } q[q_index]=count; } //松弛锚定边界条件 //计算泛函值 index=j*PointNumInPhi+k; x=energyDataPointer->pointsInSphere[0][index]; y=energyDataPointer->pointsInSphere[1][index]; z=energyDataPointer->pointsInSphere[2][index]; p[0]=q[0]*x*y-q[1]*(x*x-1.0/3); p[1]=q[1]*z-q[2]*y; p[2]=q[3]*x*y-q[1]*(y*y-1.0/3); p[3]=q[1]*z-q[4]*x; if(radius_u==PointNumInRadius){ count=0; for(i=0; i<4; i++){ count+=p[i]*p[i]; } energy += energyDataPointer->sphereInteCor[index]*count; } //计算偏导数值 dFpena_dq[0]=Eta*energyDataPointer->sphereInteCor[index]*2*(p[0]*x*y); dFpena_dq[1]=Eta*energyDataPointer->sphereInteCor[index]*2*(-p[0]*(x*x-1.0/3)+p[1]*z-p[2]*(y*y-1.0/3)+p[3]*z); dFpena_dq[2]=Eta*energyDataPointer->sphereInteCor[index]*2*(-p[1]*y); dFpena_dq[3]=Eta*energyDataPointer->sphereInteCor[index]*2*(p[2]*x*y); dFpena_dq[4]=Eta*energyDataPointer->sphereInteCor[index]*2*(-p[3]*x); for(q_index=0; q_index<5; q_index++){ for(i=radius_l; i<radius_u; i++){ energyDataPointer->dEnergy_dQ[i*PointNumInTheta*PointNumInPhi+index][q_index]=energyDataPointer->sideValVector[i] * dFpena_dq[q_index]; } } /*//强锚定边界条件 罚项 |Q-Q'|^2 //计算泛函值 index=j*PointNumInPhi+k; x=energyDataPointer->pointsInSphere[0][index]; y=energyDataPointer->pointsInSphere[1][index]; z=energyDataPointer->pointsInSphere[2][index]; q_std[0]=S*(x*x-1.0/3); q_std[1]=S*x*y; q_std[2]=S*x*z; q_std[3]=S*(y*y-1.0/3); q_std[4]=S*y*z; if(radius_u==PointNumInRadius){ count=0; for(i=0; i<5; i++){ count+=(q[i]-q_std[i])*(q[i]-q_std[i]); } energy += energyDataPointer->sphereInteCor[index]*count; } //计算偏导数值 for(i=0; i<5; i++){ dFpena_dq[i]=Eta*energyDataPointer->sphereInteCor[index]*2*(q[i]-q_std[i]); } for(q_index=0; q_index<5; q_index++){ for(i=radius_l; i<radius_u; i++){ energyDataPointer->dEnergy_dQ[i*PointNumInTheta*PointNumInPhi+index][q_index]=energyDataPointer->sideValVector[i] * dFpena_dq[q_index]; } } */ /*//罚项 |Q*x|^2 //计算泛函值 index=j*PointNumInPhi+k; x=energyDataPointer->pointsInSphere[0][index]; y=energyDataPointer->pointsInSphere[1][index]; z=energyDataPointer->pointsInSphere[2][index]; row1=q[0]*x + q[1]*y + q[2]*z; row2=q[1]*x + q[3]*y + q[4]*z; row3=q[2]*x + q[4]*y - (q[0]+q[3])*z; if(radius_u==PointNumInRadius) energy += energyDataPointer->sphereInteCor[index]*(row1*row1 + row2*row2 + row3*row3); //计算偏导数值 dFpena_dq[0]=Eta*energyDataPointer->sphereInteCor[index]*2*(row1*x - row3*z); dFpena_dq[1]=Eta*energyDataPointer->sphereInteCor[index]*2*(row1*y + row2*x); dFpena_dq[2]=Eta*energyDataPointer->sphereInteCor[index]*2*(row1*z + row3*x); dFpena_dq[3]=Eta*energyDataPointer->sphereInteCor[index]*2*(row2*y - row3*z); dFpena_dq[4]=Eta*energyDataPointer->sphereInteCor[index]*2*(row2*z + row3*y); for(q_index=0; q_index<5; q_index++){ for(i=radius_l; i<radius_u; i++){ energyDataPointer->dEnergy_dQ[i*PointNumInTheta*PointNumInPhi+index][q_index]=energyDataPointer->sideValVector[i] * dFpena_dq[q_index]; } } */ } } if(radius_u==PointNumInRadius){ energyDataPointer->energy += Eta*energy; } double* pointer1; double* pointer2; for(n=radius_l; n<radius_u; n++){ for(m=theta_l; m<theta_u; m++){ for(l=phi_l; l<phi_u; l++){ i=Point_index(n,m,l); pointer1=energyDataPointer->dQ_dBdiagAngle[i]; for(j=0; j<5; j++){ pointer2=energyDataPointer->dEnergy_dQ[i]; count=0; for(k=0; k<5; k++){ count+=(*pointer1)*(*pointer2); pointer1++; pointer2++; } energyDataPointer->dEnergy_dB[j*PointTotalNum+i]+=count; } } } } pointer1=NULL; pointer2=NULL; } void setInitValue(){ int i, j, k; //无序初值 /* for(i=0; i<5*FreeVarsUnitNum; i++){ energyDataPointer->freeVars[i]=0; } */ //随机初值 /*srand((unsigned)time(NULL)); for(i=0;i<5*PointTotalNum;i++){ energyDataPointer->Bdiag_Angle_Elements[i] = 0*(2.0*rand()/RAND_MAX - 1); }*/ //随机初值 /*srand((unsigned)time(NULL)); for(i=0;i<FreeVarsTotalNum;i++){ energyDataPointer->freeVars[i] = 2*(2.0*rand()/RAND_MAX - 1); }*/ //hedgehog初值 /*int indexBasis; for(i=0; i<PointNumInRadius; i++){ energyDataPointer->freeVars[i]=-2.375*energyDataPointer->pointInRadius[i]; for(j=0; j<PointNumInTheta; j++){ indexBasis=i*PointNumInTheta*PointNumInPhi+j*PointNumInPhi; for(k=0; k<PointNumInPhi; k++){ energyDataPointer->Bdiag_Angle_Elements[indexBasis+k+2*PointTotalNum]=0; energyDataPointer->Bdiag_Angle_Elements[indexBasis+k+3*PointTotalNum]=energyDataPointer->pointInTheta[j]; energyDataPointer->Bdiag_Angle_Elements[indexBasis+k+4*PointTotalNum]=PI/2-energyDataPointer->pointInPhi[k]; } } }*/ //hedgehog初值,ring初值 int indexBasis; for(i=0; i<PointNumInRadius; i++){ for(j=0; j<PointNumInTheta; j++){ indexBasis=i*PointNumInTheta*PointNumInPhi+j*PointNumInPhi; for(k=0; k<PointNumInPhi; k++){ energyDataPointer->Bdiag_Angle_Elements[indexBasis+k+0*PointTotalNum]=-2.375*energyDataPointer->pointInRadius[i]; energyDataPointer->Bdiag_Angle_Elements[indexBasis+k+1*PointTotalNum]=-2.375*energyDataPointer->pointInRadius[i]; energyDataPointer->Bdiag_Angle_Elements[indexBasis+k+2*PointTotalNum]=0; energyDataPointer->Bdiag_Angle_Elements[indexBasis+k+3*PointTotalNum]=energyDataPointer->pointInTheta[j]; energyDataPointer->Bdiag_Angle_Elements[indexBasis+k+4*PointTotalNum]=PI/2-energyDataPointer->pointInPhi[k]; } } } //makeFreeVars(); //sphereRing解 /*int indexBasis; for(i=0; i<PointNumInRadius; i++){ for(j=0; j<PointNumInTheta; j++){ indexBasis=i*PointNumInTheta*PointNumInPhi+j*PointNumInPhi; for(k=0; k<PointNumInPhi; k++){ energyDataPointer->Bdiag_Angle_Elements[indexBasis+k+0*PointTotalNum]=-2; energyDataPointer->Bdiag_Angle_Elements[indexBasis+k+1*PointTotalNum]=-2; energyDataPointer->Bdiag_Angle_Elements[indexBasis+k+2*PointTotalNum]=0; energyDataPointer->Bdiag_Angle_Elements[indexBasis+k+3*PointTotalNum]=0; energyDataPointer->Bdiag_Angle_Elements[indexBasis+k+4*PointTotalNum]=0; } } } //makeFreeVars();*/ //split core初值 /*int indexBasis; for(i=0; i<PointNumInRadius; i++){ for(j=0; j<PointNumInTheta; j++){ indexBasis=i*PointNumInTheta*PointNumInPhi+j*PointNumInPhi; for(k=0; k<PointNumInPhi; k++){ /*if(fabs(energyDataPointer->pointInRadius[i]*cos(energyDataPointer->pointInTheta[j]))<SplitCorePoint){ energyDataPointer->Bdiag_Angle_Elements[indexBasis+k+0*PointTotalNum]=-1*energyDataPointer->pointInRadius[i]-0.5; energyDataPointer->Bdiag_Angle_Elements[indexBasis+k+1*PointTotalNum]=-1*energyDataPointer->pointInRadius[i]-0.5; energyDataPointer->Bdiag_Angle_Elements[indexBasis+k+2*PointTotalNum]=0; energyDataPointer->Bdiag_Angle_Elements[indexBasis+k+3*PointTotalNum]=PI/2; energyDataPointer->Bdiag_Angle_Elements[indexBasis+k+4*PointTotalNum]=PI/2-energyDataPointer->pointInPhi[k]; } else{ energyDataPointer->Bdiag_Angle_Elements[indexBasis+k+0*PointTotalNum]=-2*(energyDataPointer->pointInRadius[i]-SplitCorePoint); energyDataPointer->Bdiag_Angle_Elements[indexBasis+k+1*PointTotalNum]=-2*(energyDataPointer->pointInRadius[i]-SplitCorePoint); energyDataPointer->Bdiag_Angle_Elements[indexBasis+k+2*PointTotalNum]=0; if(energyDataPointer->pointInTheta[j]<PI/2){ energyDataPointer->Bdiag_Angle_Elements[indexBasis+k+3*PointTotalNum]=atan(energyDataPointer->pointInRadius[i]*sin(energyDataPointer->pointInTheta[j])/(energyDataPointer->pointInRadius[i]*cos(energyDataPointer->pointInTheta[j])-SplitCorePoint)); } else{ energyDataPointer->Bdiag_Angle_Elements[indexBasis+k+3*PointTotalNum]=atan(energyDataPointer->pointInRadius[i]*sin(energyDataPointer->pointInTheta[j])/(energyDataPointer->pointInRadius[i]*cos(energyDataPointer->pointInTheta[j])+SplitCorePoint))+PI; } energyDataPointer->Bdiag_Angle_Elements[indexBasis+k+4*PointTotalNum]=PI/2-energyDataPointer->pointInPhi[k]; }* if(energyDataPointer->pointInRadius[i]<0.9){ energyDataPointer->Bdiag_Angle_Elements[indexBasis+k+0*PointTotalNum]=5; energyDataPointer->Bdiag_Angle_Elements[indexBasis+k+1*PointTotalNum]=5; } else{ energyDataPointer->Bdiag_Angle_Elements[indexBasis+k+0*PointTotalNum]=-2*energyDataPointer->pointInRadius[i]; energyDataPointer->Bdiag_Angle_Elements[indexBasis+k+1*PointTotalNum]=-2*energyDataPointer->pointInRadius[i]; } energyDataPointer->Bdiag_Angle_Elements[indexBasis+k+2*PointTotalNum]=0; energyDataPointer->Bdiag_Angle_Elements[indexBasis+k+3*PointTotalNum]=energyDataPointer->pointInTheta[j]; energyDataPointer->Bdiag_Angle_Elements[indexBasis+k+4*PointTotalNum]=PI/2-energyDataPointer->pointInPhi[k]; } } } //makeFreeVars();*/ //读取已有结果 /*FILE* fp; if((fp=fopen("result/B.txt","r"))==NULL) exit(1); for(i=0; i<5*PointTotalNum; i++){ fscanf(fp, "%lf ", &energyDataPointer->Bdiag_Angle_Elements[i]); } fclose(fp); //makeFreeVars();*/ }
yixiangLuo/Liquid_Crystal
initEnergySpace.c
#include "initEnergySpace.h" #include <stdlib.h> #include <stdio.h> #include <math.h> #include "gaussian_nodes.h" void energySpaceFree(energySpace* energyDataPointer){ int i; if(!energyDataPointer) return; //释放自由变量 //free((void *)energyDataPointer->freeVars); //释放自变量B free((void *)energyDataPointer->Bdiag_Angle_Elements); //释放Q的特征值 free((void *)energyDataPointer->Qdiag_elements); //释放Q free((void *)energyDataPointer->Q_elements); //释放Z free((void *)energyDataPointer->Z_elements); //释放Z关于B的特征值的偏导数 freeMatrixSpace(energyDataPointer->dZ_dBdiag, 2); //释放Q的特征值关于B的特征值的偏导数 freeMatrixSpace(energyDataPointer->dQdiag_dBdiag, 4); //释放Q关于B的偏导数 freeMatrixSpace(energyDataPointer->dQ_dBdiagAngle, PointTotalNum); //释放能量积分关于自变量B的偏导数 free((void *)energyDataPointer->dEnergy_dB); //释放能量积分关于自由变量的偏导数 //free((void *)energyDataPointer->dEnergy_freeVars); //释放r方向上的节点 free((void *)energyDataPointer->pointInRadius); //释放theta方向上的节点 free((void *)energyDataPointer->pointInTheta); //释放phi方向上的节点 free((void *)energyDataPointer->pointInPhi); //释放单位球内的数值积分节点 freeMatrixSpace(energyDataPointer->pointsInBall, 3); //释放单位球面上的数值积分节点 freeMatrixSpace(energyDataPointer->pointsInSphere, 3); //释放单位球内的数值积分系数 free((void *)energyDataPointer->ballInteCor); //释放单位球面上的数值积分系数 free((void *)energyDataPointer->sphereInteCor); //多项式方法 //释放求偏导数的转换矩阵 radius方向 freeMatrixSpace(energyDataPointer->gradMatrix_radius, PointNumInRadius); //释放求偏导数的转换矩阵 theta方向 freeMatrixSpace(energyDataPointer->gradMatrix_theta, PointNumInTheta); //释放求偏导数的转换矩阵 phi方向 freeMatrixSpace(energyDataPointer->gradMatrix_phi, PointNumInPhi); //释放计算球面上函数值的系数向量(r方向) free((void *)energyDataPointer->sideValVector); //释放存储中间值的空间 free((void *)energyDataPointer->dQ_drtp); free((void *)energyDataPointer->dEnergy_dQdrtp); free((void *)energyDataPointer->dEnergy_dQ); //释放结构体 free((void *)energyDataPointer); return ; } energySpace* initEnergySpace(){ double* p ; FILE* fp; int i, j, n, m, l; double deno, nume, temp; double gaussian_node[64][100] = Gaussian_Nodes; double gaussian_weight[64][100] = Gaussian_Weights; //分配指针结构体 energySpace* energyDataPointer = (energySpace*) malloc(sizeof(energySpace)); if(energyDataPointer==NULL){ printf("fail to initiate energy space: menmory not enough!\n"); exit(1); } //初始化 //energyDataPointer->freeVars=NULL; energyDataPointer->Bdiag_Angle_Elements=NULL; energyDataPointer->Qdiag_elements=NULL; energyDataPointer->Q_elements=NULL; energyDataPointer->Z_elements=NULL; energyDataPointer->dZ_dBdiag=NULL; energyDataPointer->dQdiag_dBdiag=NULL; energyDataPointer->dQ_dBdiagAngle=NULL; energyDataPointer->dEnergy_dB=NULL; //energyDataPointer->dEnergy_freeVars=NULL; energyDataPointer->pointInRadius=NULL; energyDataPointer->pointInTheta=NULL; energyDataPointer->pointInPhi=NULL; energyDataPointer->pointsInBall=NULL; energyDataPointer->pointsInSphere=NULL; energyDataPointer->ballInteCor=NULL; energyDataPointer->sphereInteCor=NULL; //多项式方法 energyDataPointer->gradMatrix_radius=NULL; energyDataPointer->gradMatrix_theta=NULL; energyDataPointer->gradMatrix_phi=NULL; energyDataPointer->sideValVector=NULL; //存储计算中间值 energyDataPointer->dQ_drtp=NULL; energyDataPointer->dEnergy_dQdrtp=NULL; energyDataPointer->dEnergy_dQ=NULL; //分配自由变量的存储空间 //energyDataPointer->freeVars = linearSpace_Energy(FreeVarsTotalNum, energyDataPointer); //分配自变量B的存储空间 energyDataPointer->Bdiag_Angle_Elements = linearSpace_Energy(5*PointTotalNum, energyDataPointer); //分配Q的特征值的存储空间 energyDataPointer->Qdiag_elements = linearSpace_Energy(2*PointTotalNum, energyDataPointer); //分配Q的存储空间 energyDataPointer->Q_elements = linearSpace_Energy(5*PointTotalNum, energyDataPointer); //分配Z的存储空间 energyDataPointer->Z_elements = linearSpace_Energy(PointTotalNum, energyDataPointer); //分配Z关于B的特征值的偏导数的存储空间 energyDataPointer->dZ_dBdiag = matrixSpace_Energy(2, PointTotalNum, energyDataPointer); //分配Q的特征值关于B的特征值的偏导数的存储空间 energyDataPointer->dQdiag_dBdiag = matrixSpace_Energy(4, PointTotalNum, energyDataPointer); //分配Q关于B的偏导数的存储空间 energyDataPointer->dQ_dBdiagAngle = matrixSpace_Energy(PointTotalNum, 25, energyDataPointer); //分配能量积分关于自变量B的偏导数的存储空间 energyDataPointer->dEnergy_dB = linearSpace_Energy(5*PointTotalNum, energyDataPointer); //分配能量积分关于自由变量的偏导数的存储空间 //energyDataPointer->dEnergy_freeVars = linearSpace_Energy(FreeVarsTotalNum, energyDataPointer); //分配并计算r方向上的节点 energyDataPointer->pointInRadius = linearSpace_Energy(PointNumInRadius, energyDataPointer); //计算 for(i=0; i<PointNumInRadius; i++){ energyDataPointer->pointInRadius[i] = 1.0/2*gaussian_node[Gaussian_index(PointNumInRadius)][i] + 0.5; } //分配并计算theta方向上的节点 energyDataPointer->pointInTheta = linearSpace_Energy(PointNumInTheta, energyDataPointer); //计算 for(i=0; i<PointNumInTheta; i++){ energyDataPointer->pointInTheta[i] = PI/2.0*gaussian_node[Gaussian_index(PointNumInTheta)][i] + PI/2.0; } //分配并计算theta方向上的节点 energyDataPointer->pointInPhi = linearSpace_Energy(PointNumInPhi, energyDataPointer); //计算 for(i=0; i<PointNumInPhi; i++){ energyDataPointer->pointInPhi[i] = PI*gaussian_node[Gaussian_index(PointNumInPhi)][i] + PI; } //分配并计算单位球中的数值积分节点 energyDataPointer->pointsInBall = matrixSpace_Energy(3, PointTotalNum, energyDataPointer); //计算 for(n=0; n<PointNumInRadius; n++){ for(m=0; m<PointNumInTheta; m++){ for(l=0; l<PointNumInPhi; l++){ energyDataPointer->pointsInBall[0][Point_index(n,m,l)] = energyDataPointer->pointInRadius[n]*sin(energyDataPointer->pointInTheta[m])*cos(energyDataPointer->pointInPhi[l]); energyDataPointer->pointsInBall[1][Point_index(n,m,l)] = energyDataPointer->pointInRadius[n]*sin(energyDataPointer->pointInTheta[m])*sin(energyDataPointer->pointInPhi[l]); energyDataPointer->pointsInBall[2][Point_index(n,m,l)] = energyDataPointer->pointInRadius[n]*cos(energyDataPointer->pointInTheta[m]); } } } //分配并计算单位球面上的数值积分节点 energyDataPointer->pointsInSphere = matrixSpace_Energy(3, PointNumInTheta*PointNumInPhi, energyDataPointer); //计算 for(m=0; m<PointNumInTheta; m++){ for(l=0; l<PointNumInPhi; l++){ energyDataPointer->pointsInSphere[0][m*PointNumInPhi+l] = sin(energyDataPointer->pointInTheta[m])*cos(energyDataPointer->pointInPhi[l]); energyDataPointer->pointsInSphere[1][m*PointNumInPhi+l] = sin(energyDataPointer->pointInTheta[m])*sin(energyDataPointer->pointInPhi[l]); energyDataPointer->pointsInSphere[2][m*PointNumInPhi+l] = cos(energyDataPointer->pointInTheta[m]); } } //分配并计算单位球中的数值积分系数 energyDataPointer->ballInteCor = linearSpace_Energy(PointTotalNum, energyDataPointer); //计算 for(n=0; n<PointNumInRadius; n++){ for(m=0; m<PointNumInTheta; m++){ for(l=0; l<PointNumInPhi; l++){ energyDataPointer->ballInteCor[Point_index(n,m,l)] = energyDataPointer->pointInRadius[n]*energyDataPointer->pointInRadius[n]*1.0/2*gaussian_weight[Gaussian_index(PointNumInRadius)][n] * sin(energyDataPointer->pointInTheta[m])*PI/2.0*gaussian_weight[Gaussian_index(PointNumInTheta)][m] * PI*gaussian_weight[Gaussian_index(PointNumInPhi)][l]; } } } //分配并计算单位球面上的数值积分系数 energyDataPointer->sphereInteCor = linearSpace_Energy(PointNumInTheta*PointNumInPhi, energyDataPointer); //计算 for(m=0; m<PointNumInTheta; m++){ for(l=0; l<PointNumInPhi; l++){ energyDataPointer->sphereInteCor[m*PointNumInPhi+l] = sin(energyDataPointer->pointInTheta[m])*PI/2.0*gaussian_weight[Gaussian_index(PointNumInTheta)][m] * PI*gaussian_weight[Gaussian_index(PointNumInPhi)][l]; } } //多项式方法 //分配并计算求偏导数的转换矩阵 radius方向 energyDataPointer->gradMatrix_radius = matrixSpace_Energy(PointNumInRadius, PointNumInRadius, energyDataPointer); //计算 for(n=0; n<PointNumInRadius; n++){ deno=1; for(i=0; i<PointNumInRadius; i++){ if(i!=n) deno *= (energyDataPointer->pointInRadius[n]-energyDataPointer->pointInRadius[i]); } for(m=0; m<PointNumInRadius; m++){ nume=0; for(l=0; l<PointNumInRadius; l++){ if(l==n) continue; temp=1; for(i=0; i<PointNumInRadius; i++){ if(i!=n && i!=l) temp *= (energyDataPointer->pointInRadius[m]-energyDataPointer->pointInRadius[i]); } nume+=temp; } energyDataPointer->gradMatrix_radius[m][n]=nume/deno; } } //分配并计算求偏导数的转换矩阵 theta方向 energyDataPointer->gradMatrix_theta = matrixSpace_Energy(PointNumInTheta, PointNumInTheta, energyDataPointer); //计算 for(n=0; n<PointNumInTheta; n++){ deno=1; for(i=0; i<PointNumInTheta; i++){ if(i!=n) deno *= (energyDataPointer->pointInTheta[n]-energyDataPointer->pointInTheta[i]); } for(m=0; m<PointNumInTheta; m++){ nume=0; for(l=0; l<PointNumInTheta; l++){ if(l==n) continue; temp=1; for(i=0; i<PointNumInTheta; i++){ if(i!=n && i!=l) temp *= (energyDataPointer->pointInTheta[m]-energyDataPointer->pointInTheta[i]); } nume+=temp; } energyDataPointer->gradMatrix_theta[m][n]=nume/deno; } } //分配并计算求偏导数的转换矩阵 phi方向 energyDataPointer->gradMatrix_phi = matrixSpace_Energy(PointNumInPhi, PointNumInPhi, energyDataPointer); //计算 for(n=0; n<PointNumInPhi; n++){ deno=1; for(i=0; i<PointNumInPhi; i++){ if(i!=n) deno *= (energyDataPointer->pointInPhi[n]-energyDataPointer->pointInPhi[i]); } for(m=0; m<PointNumInPhi; m++){ nume=0; for(l=0; l<PointNumInPhi; l++){ if(l==n) continue; temp=1; for(i=0; i<PointNumInPhi; i++){ if(i!=n && i!=l) temp *= (energyDataPointer->pointInPhi[m]-energyDataPointer->pointInPhi[i]); } nume+=temp; } energyDataPointer->gradMatrix_phi[m][n]=nume/deno; } } //分配并计算计算球面上函数值的系数向量(r方向) energyDataPointer->sideValVector = linearSpace_Energy(PointNumInRadius, energyDataPointer); //计算 for(n=0; n<PointNumInRadius; n++){ deno=1; nume=1; for(i=0; i<PointNumInRadius; i++){ if(i==n) continue; deno *= (energyDataPointer->pointInRadius[n]-energyDataPointer->pointInRadius[i]); nume *= (1-energyDataPointer->pointInRadius[i]); } energyDataPointer->sideValVector[n]=nume/deno; } //分配存储计算中间值的空间 energyDataPointer->dQ_drtp=matrixSpace_Energy(3, 5*PointTotalNum, energyDataPointer); energyDataPointer->dEnergy_dQdrtp=matrixSpace_Energy(3, 5*PointTotalNum, energyDataPointer); energyDataPointer->dEnergy_dQ=matrixSpace_Energy(PointTotalNum, 5, energyDataPointer); return energyDataPointer; } double* linearSpace_Energy(int size, energySpace* energyDataPointer){ double* dataSpace = (double*) malloc(size*sizeof(double)); if(dataSpace==NULL){ energySpaceFree(energyDataPointer); printf("fail to allocate temp space: menmory not enough!\n"); exit(1); } return dataSpace; } void freeMatrixSpace(double** dataSpace, int row){ int i; if(dataSpace){ for(i=0;i<row;i++){ free((void *)dataSpace[i]); } } free((void *)dataSpace); } double** matrixSpace_Energy(int row, int col, energySpace* energyDataPointer){ int i; double** dataSpace = (double **) malloc(row * sizeof(double * )); if(dataSpace==NULL){ energySpaceFree(energyDataPointer); printf("fail to allocate temp space: menmory not enough!\n"); exit(1); } for(i=0;i<row;i++) dataSpace[i] = NULL; for(i=0;i<row;i++){ dataSpace[i] = (double*) malloc(col * sizeof(double)); if(dataSpace[i]==NULL){ energySpaceFree(energyDataPointer); printf("fail to allocate temp space: menmory not enough!\n"); exit(1); } } return dataSpace; }
yixiangLuo/Liquid_Crystal
main.c
#include <stdlib.h> #include <stdio.h> #include <mpi.h> #include <math.h> #include <string.h> #include <time.h> #include "header.h" #include "initEnergySpace.h" #include "bingham.h" #include "calcEnergy.h" #include "para_lbfgs.h" energySpace* energyDataPointer; binghamDataSpace* binghamDataPointer; mpi_comm_data* mpi_comm_space; clock_t comm_time = 0; clock_t comm_start, comm_end; void outPut(); double para_norm(double* vector, int dim) { int i; double norm, norm_reduce; norm = 0; for(i=0;i<dim;i++){ norm += vector[i]*vector[i]; } MPI_Allreduce(&norm, &norm_reduce, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); norm = sqrt(norm_reduce); return norm; } static lbfgsfloatval_t evaluate( void *instance, const double* x, double* grad, const int n, const lbfgsfloatval_t step ) { int i; double energy; energy = eval_energy(); for(i=0;i<5*PointTotalNum;i++){ grad[i]=energyDataPointer->dEnergy_dB[i]; } return energy; } static int progress( void *instance, const double* freeVars, const double* dEnergy_dFreeVars, const double Energy, const lbfgsfloatval_t xnorm, const lbfgsfloatval_t gnorm, const lbfgsfloatval_t step, int n, int k, int ls ) { int i, rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); if(k%10 == 0 && rank==0){ printf("Iteration %d: ",k); printf("Energy = %-16.15f ",Energy); printf("normX = %-10.8f normdF = %-10.9f step = %-10.8f\n", xnorm, gnorm, step); } if (k%500 == 0){ //outPut(); } return 0; } int main(int argc, char** argv) { MPI_Init(&argc, &argv); int rank, stop; MPI_Comm_rank(MPI_COMM_WORLD, &rank); mpi_comm_space = mpi_init_space(); energyDataPointer=initEnergySpace(); binghamDataPointer=initiateBingham(); setInitValue(); int ret = 0; double Energy; lbfgs_parameter_t param; lbfgs_parameter_init(&param); param.m = 10; param.delta = 0; param.epsilon = 1e-5; param.max_iterations = 10000; param.max_linesearch = 50; param.linesearch = LBFGS_LINESEARCH_BACKTRACKING_WOLFE; param.ftol = 1e-4; param.wolfe = 0.9; clock_t start, finish; start = clock(); ret = lbfgs(5*PointTotalNum, energyDataPointer->Bdiag_Angle_Elements, &Energy, evaluate, progress, NULL, &param); finish = clock(); double norm = para_norm(energyDataPointer->Bdiag_Angle_Elements,5*PointTotalNum); FILE* fp; char filename[100]; char number[10]; if(rank==0){ strcpy(filename, "LC_Timing_"); sprintf(number, "%d_" , PointNumInRadius); strcat(filename, number); sprintf(number, "%d_" , PointNumInTheta); strcat(filename, number); sprintf(number, "%d__" , PointNumInPhi); strcat(filename, number); sprintf(number, "%d_" , RadiusSlice); strcat(filename, number); sprintf(number, "%d_" , ThetaSlice); strcat(filename, number); sprintf(number, "%d.txt" , PhiSlice); strcat(filename, number); if((fp=fopen(filename,"wt"))==NULL){ printf("Cannot open file strike any key exit!"); exit(1); } fprintf(fp, "\nL-BFGS optimization terminated with status code = %d\n", ret); fprintf(fp, "Energy = %-20.19f normX = %-20.19f\n", Energy, norm); fprintf(fp, "total time: %.6f seconds\n", (double)(finish - start) / CLOCKS_PER_SEC); fprintf(fp, "communication time: %.6f seconds. %.2f%% \n", (double)(comm_time)/CLOCKS_PER_SEC, (double)comm_time / (finish - start)*100); fclose(fp); //outPut(); } mpi_free_space(mpi_comm_space); binghamDataFree(binghamDataPointer); energySpaceFree(energyDataPointer); MPI_Finalize(); return 0; } void outPut(){ int i, j; double* p; FILE* fp; /*p=energyDataPointer->freeVars; if((fp=fopen("result/freeVars.txt","wt"))==NULL){ printf("Cannot open file strike any key exit!"); exit(1); } for(i=0; i<FreeVarsTotalNum; i++){ fprintf(fp, "%.16f ", *p); p++; } fclose(fp); */ if((fp=fopen("result/energy.txt","wt"))==NULL){ printf("Cannot open file strike any key exit!"); exit(1); } fprintf(fp, "%.16f ", energyDataPointer->energy); fclose(fp); p=energyDataPointer->Bdiag_Angle_Elements; if((fp=fopen("result/B.txt","wt"))==NULL){ printf("Cannot open file strike any key exit!"); exit(1); } for(i=0; i<5*PointTotalNum; i++){ fprintf(fp, "%.16f ", *p); if((i+1)%PointTotalNum==0) fprintf(fp, "\n"); p++; } fclose(fp); p=energyDataPointer->Qdiag_elements; if((fp=fopen("result/Q_eigVal.txt","wt"))==NULL){ printf("Cannot open file strike any key exit!"); exit(1); } for(i=0; i<2*PointTotalNum; i++){ fprintf(fp, "%.16f ", *p); if((i+1)%PointTotalNum==0) fprintf(fp, "\n"); p++; } fclose(fp); p=energyDataPointer->Q_elements; if((fp=fopen("result/Q.txt","wt"))==NULL){ printf("Cannot open file strike any key exit!"); exit(1); } for(i=0; i<5*PointTotalNum; i++){ fprintf(fp, "%.16f ", *p); if((i+1)%PointTotalNum==0) fprintf(fp, "\n"); p++; } fclose(fp); p=energyDataPointer->Z_elements; if((fp=fopen("result/Z.txt","wt"))==NULL){ printf("Cannot open file strike any key exit!"); exit(1); } for(i=0; i<PointTotalNum; i++){ fprintf(fp, "%.16f ", *p); if((i+1)%PointTotalNum==0) fprintf(fp, "\n"); p++; } fclose(fp); p=energyDataPointer->dEnergy_dB; if((fp=fopen("result/dEnergy_dB.txt","wt"))==NULL){ printf("Cannot open file strike any key exit!"); exit(1); } for(i=0; i<5*PointTotalNum; i++){ fprintf(fp, "%.16f ", *p); if((i+1)%PointTotalNum==0) fprintf(fp, "\n"); p++; } fclose(fp); if((fp=fopen("result/dZ_dBdiag.txt","a+"))==NULL){ printf("Cannot open file strike any key exit!"); exit(1); } for(i=0;i<2;i++){ p=energyDataPointer->dZ_dBdiag[i]; for(j=0; j<PointTotalNum; j++){ fprintf(fp, "%.16f ", *p); p++; } } fclose(fp); if((fp=fopen("result/dQdiag_dBdiag.txt","a+"))==NULL){ printf("Cannot open file strike any key exit!"); exit(1); } for(i=0;i<4;i++){ p=energyDataPointer->dQdiag_dBdiag[i]; for(j=0; j<PointTotalNum; j++){ fprintf(fp, "%.16f ", *p); p++; } } fclose(fp); if((fp=fopen("result/dQ_dBdiagAngle.txt","a+"))==NULL){ printf("Cannot open file strike any key exit!"); exit(1); } for(i=0;i<PointTotalNum;i++){ p=energyDataPointer->dQ_dBdiagAngle[i]; for(j=0; j<25; j++){ fprintf(fp, "%.16f ", *p); p++; } } fclose(fp); }
yixiangLuo/Liquid_Crystal
calcEnergy.h
#ifndef CALCENERGY_H #define CALCENERGY_H #include <mpi.h> #define Radius_Low(rank) ((rank)/(ThetaSlice*PhiSlice)*(PointNumInRadius/RadiusSlice)) #define Radius_Up(rank) (((rank)/(ThetaSlice*PhiSlice)+1)*(PointNumInRadius/RadiusSlice)) #define Theta_Low(rank) ((rank)%(ThetaSlice*PhiSlice)/PhiSlice*(PointNumInTheta/ThetaSlice)) #define Theta_Up(rank) (((rank)%(ThetaSlice*PhiSlice)/PhiSlice+1)*(PointNumInTheta/ThetaSlice)) #define Phi_Low(rank) ((rank)%PhiSlice*(PointNumInPhi/PhiSlice)) #define Phi_Up(rank) (((rank)%PhiSlice+1)*(PointNumInPhi/PhiSlice)) typedef struct mpi_comm_data{ MPI_Comm* mpi_comm_groups; double* mpi_msg_send; double* mpi_msg_rec; int local_total_num; } mpi_comm_data; mpi_comm_data* mpi_init_space(); void mpi_free_space(mpi_comm_data* mpi_comm_space); double* linearSpace_MPI(int size, mpi_comm_data* mpi_comm_space); void exchange_vals(int rank, double** src, double** des, mpi_comm_data* mpi_comm_space, int same); //void makeB(); //void makeFreeVars(); //void transVarsBack(); double eval_energy(); void preCalculate(int rank); void calc_Q_dQdB(int i); void calc_Fbulk(int rank); void calc_Felas(int rank); void calc_Fpena(int rank); void setInitValue(); #endif
yixiangLuo/Liquid_Crystal
initEnergySpace.h
<reponame>yixiangLuo/Liquid_Crystal #ifndef INITENERGYSPACE_H #define INITENERGYSPACE_H #include "header.h" energySpace* initEnergySpace(); void energySpaceFree(energySpace* energyDataPointer); double* linearSpace_Energy(int size, energySpace* energyDataPointer); void freeMatrixSpace(double** dataSpace, int row); double** matrixSpace_Energy(int row, int col, energySpace* energyDataPointer); #endif
yixiangLuo/Liquid_Crystal
bingham.c
#include "bingham.h" #include <stdlib.h> #include <stdio.h> #include <math.h> /* 2D interpolation function */ double hermiteInterpolate(double areaSpacing, double x1, double x2, double y1, double y2, double f11, double f12, double f21, double f22, double f11dx, double f12dx, double f21dx, double f22dx, double f11dy, double f12dy, double f21dy, double f22dy, double x, double y){ double areaSpacingHalf=areaSpacing/2, areaSpacingSquare=areaSpacing*areaSpacing; double sepaX1=x-x1, sepaX2=x-x2; double squareX1=sepaX2*sepaX2/areaSpacingSquare, squareX2=sepaX1*sepaX1/areaSpacingSquare; double betaX1=sepaX1*squareX1, betaX2=sepaX2*squareX2; double alphaX1=betaX1/areaSpacingHalf+squareX1, alphaX2=-betaX2/areaSpacingHalf+squareX2; double sepaY1=y-y1, sepaY2=y-y2; double squareY1=sepaY2*sepaY2/areaSpacingSquare, squareY2=sepaY1*sepaY1/areaSpacingSquare; double betaY1=sepaY1*squareY1, betaY2=sepaY2*squareY2; double alphaY1=betaY1/areaSpacingHalf+squareY1, alphaY2=-betaY2/areaSpacingHalf+squareY2; double fd=f11*alphaX1+f21*alphaX2+f11dx*betaX1+f21dx*betaX2; double fu=f12*alphaX1+f22*alphaX2+f12dx*betaX1+f22dx*betaX2; double fl=f11*alphaY1+f12*alphaY2+f11dy*betaY1+f12dy*betaY2; double fr=f21*alphaY1+f22*alphaY2+f21dy*betaY1+f22dy*betaY2; double fddB2=(f21dy-f11dy)/areaSpacing*sepaX1+f11dy; double fudB2=(f22dy-f12dy)/areaSpacing*sepaX1+f12dy; double fldB1=(f12dx-f11dx)/areaSpacing*sepaY1+f11dx; double frdB1=(f22dx-f21dx)/areaSpacing*sepaY1+f21dx; double rowVal=fl*alphaX1+fr*alphaX2+fldB1*betaX1+frdB1*betaX2; double colVal=fd*alphaY1+fu*alphaY2+fddB2*betaY1+fudB2*betaY2; return (rowVal+colVal)/2; } /* 1D interpolation function */ double calcDerivative(double x, int order, double** finite1D){ int index=(int) (-x/LinearSpacing); order=order/2; return finite1D[order][index]+(-x-index*LinearSpacing)*(finite1D[order][index+1]-finite1D[order][index])/LinearSpacing; } /* sort the input array b in a increasing order and record its original order */ void sort(double (*array)[3], int rowNum){ int i,j; int min_idx; double temp; for(j=0; j<2; j++){ min_idx = j; for(i=j+1; i<3; i++){ if(array[0][i] < array[0][min_idx]) min_idx = i; } for(i=0; i<rowNum; i++){ temp=array[i][j]; array[i][j]=array[i][min_idx]; array[i][min_idx]=temp; } } } /* release the heap memory allocated for the data structure. */ void binghamDataFree(binghamDataSpace* binghamDataPointer){ int i; if(!binghamDataPointer) return; if(binghamDataPointer->binghamVal_Z){ for(i=0;i<InterpNodesNumAxis_2D_Z;i++){ free((void *)binghamDataPointer->binghamVal_Z[i]); } } free((void *)binghamDataPointer->binghamVal_Z); if(binghamDataPointer->dB1Bingham_Z){ for(i=0;i<InterpNodesNumAxis_2D_Z;i++){ free((void *)binghamDataPointer->dB1Bingham_Z[i]); } } free((void *)binghamDataPointer->dB1Bingham_Z); if(binghamDataPointer->dB2Bingham_Z){ for(i=0;i<InterpNodesNumAxis_2D_Z;i++){ free((void *)binghamDataPointer->dB2Bingham_Z[i]); } } free((void *)binghamDataPointer->dB2Bingham_Z); if(binghamDataPointer->binghamVal_Z_x12){ for(i=0;i<InterpNodesNumAxis_2D_Z;i++){ free((void *)binghamDataPointer->binghamVal_Z_x12[i]); } } free((void *)binghamDataPointer->binghamVal_Z_x12); if(binghamDataPointer->dB1Bingham_Z_x12){ for(i=0;i<InterpNodesNumAxis_2D_Z;i++){ free((void *)binghamDataPointer->dB1Bingham_Z_x12[i]); } } free((void *)binghamDataPointer->dB1Bingham_Z_x12); if(binghamDataPointer->dB2Bingham_Z_x12){ for(i=0;i<InterpNodesNumAxis_2D_Z;i++){ free((void *)binghamDataPointer->dB2Bingham_Z_x12[i]); } } free((void *)binghamDataPointer->dB2Bingham_Z_x12); if(binghamDataPointer->binghamVal_Q_x14){ for(i=0;i<InterpNodesNumAxis_2D_Q;i++){ free((void *)binghamDataPointer->binghamVal_Q_x14[i]); } } free((void *)binghamDataPointer->binghamVal_Q_x14); if(binghamDataPointer->dB1Bingham_Q_x14){ for(i=0;i<InterpNodesNumAxis_2D_Q;i++){ free((void *)binghamDataPointer->dB1Bingham_Q_x14[i]); } } free((void *)binghamDataPointer->dB1Bingham_Q_x14); if(binghamDataPointer->dB2Bingham_Q_x14){ for(i=0;i<InterpNodesNumAxis_2D_Q;i++){ free((void *)binghamDataPointer->dB2Bingham_Q_x14[i]); } } free((void *)binghamDataPointer->dB2Bingham_Q_x14); if(binghamDataPointer->binghamVal_Q_x12x22){ for(i=0;i<InterpNodesNumAxis_2D_Q;i++){ free((void *)binghamDataPointer->binghamVal_Q_x12x22[i]); } } free((void *)binghamDataPointer->binghamVal_Q_x12x22); if(binghamDataPointer->dB1Bingham_Q_x12x22){ for(i=0;i<InterpNodesNumAxis_2D_Q;i++){ free((void *)binghamDataPointer->dB1Bingham_Q_x12x22[i]); } } free((void *)binghamDataPointer->dB1Bingham_Q_x12x22); if(binghamDataPointer->dB2Bingham_Q_x12x22){ for(i=0;i<InterpNodesNumAxis_2D_Q;i++){ free((void *)binghamDataPointer->dB2Bingham_Q_x12x22[i]); } } free((void *)binghamDataPointer->dB2Bingham_Q_x12x22); if(binghamDataPointer->finite1D_x0){ for(i=0;i<7;i++){ free((void *)binghamDataPointer->finite1D_x0[i]); } } free((void *)binghamDataPointer->finite1D_x0); if(binghamDataPointer->finite1D_x2){ for(i=0;i<7;i++){ free((void *)binghamDataPointer->finite1D_x2[i]); } } free((void *)binghamDataPointer->finite1D_x2); if(binghamDataPointer->finite1D_x4){ for(i=0;i<7;i++){ free((void *)binghamDataPointer->finite1D_x4[i]); } } free((void *)binghamDataPointer->finite1D_x4); free((void *)binghamDataPointer); return ; } /* allocate heap memory for the data structure and read in the data from binghamData.bi */ binghamDataSpace* initiateBingham(){ FILE* fp; int i; /* allocate heap memory for the data structure pointer */ binghamDataSpace* binghamDataPointer = (binghamDataSpace*) malloc(sizeof(binghamDataSpace)); if(binghamDataPointer==NULL){ printf("fail to initiate bingham data space: menmory not enough!\n"); exit(1); } /* initialize the pointers */ binghamDataPointer->binghamVal_Z=NULL; binghamDataPointer->dB1Bingham_Z=NULL; binghamDataPointer->dB2Bingham_Z=NULL; binghamDataPointer->binghamVal_Z_x12=NULL; binghamDataPointer->dB1Bingham_Z_x12=NULL; binghamDataPointer->dB2Bingham_Z_x12=NULL; binghamDataPointer->binghamVal_Q_x14=NULL; binghamDataPointer->dB1Bingham_Q_x14=NULL; binghamDataPointer->dB2Bingham_Q_x14=NULL; binghamDataPointer->binghamVal_Q_x12x22=NULL; binghamDataPointer->dB1Bingham_Q_x12x22=NULL; binghamDataPointer->dB2Bingham_Q_x12x22=NULL; binghamDataPointer->finite1D_x0=NULL; binghamDataPointer->finite1D_x2=NULL; binghamDataPointer->finite1D_x4=NULL; /* open binghamData.bi */ if((fp=fopen("binghamData.bi","rb+"))==NULL){ binghamDataFree(binghamDataPointer); printf("Cannot open file strike any key exit!"); exit(1); } /* allocate heap memory for each pointer and read in the data. */ binghamDataPointer->binghamVal_Z = (double **) malloc(InterpNodesNumAxis_2D_Z * sizeof(double * )); if(binghamDataPointer->binghamVal_Z==NULL){ binghamDataFree(binghamDataPointer); printf("fail to initiate bingham data space: menmory not enough!\n"); exit(1); } for(i=0;i<InterpNodesNumAxis_2D_Z;i++) binghamDataPointer->binghamVal_Z[i] = NULL; for(i=0;i<InterpNodesNumAxis_2D_Z;i++){ binghamDataPointer->binghamVal_Z[i] = (double*) malloc(InterpNodesNumAxis_2D_Z * sizeof(double)); if(binghamDataPointer->binghamVal_Z[i]==NULL){ binghamDataFree(binghamDataPointer); printf("fail to initiate bingham data space: menmory not enough!\n"); exit(1); } } for(i=0; i<InterpNodesNumAxis_2D_Z; i++){ fread(binghamDataPointer->binghamVal_Z[i], sizeof(double), InterpNodesNumAxis_2D_Z, fp); } binghamDataPointer->dB1Bingham_Z = (double **) malloc(InterpNodesNumAxis_2D_Z * sizeof(double * )); if(binghamDataPointer->dB1Bingham_Z==NULL){ binghamDataFree(binghamDataPointer); printf("fail to initiate bingham data space: menmory not enough!\n"); exit(1); } for(i=0;i<InterpNodesNumAxis_2D_Z;i++) binghamDataPointer->dB1Bingham_Z[i] = NULL; for(i=0;i<InterpNodesNumAxis_2D_Z;i++){ binghamDataPointer->dB1Bingham_Z[i] = (double*) malloc(InterpNodesNumAxis_2D_Z * sizeof(double)); if(binghamDataPointer->dB1Bingham_Z[i]==NULL){ binghamDataFree(binghamDataPointer); printf("fail to initiate bingham data space: menmory not enough!\n"); exit(1); } } for(i=0; i<InterpNodesNumAxis_2D_Z; i++){ fread(binghamDataPointer->dB1Bingham_Z[i], sizeof(double), InterpNodesNumAxis_2D_Z, fp); } binghamDataPointer->dB2Bingham_Z = (double **) malloc(InterpNodesNumAxis_2D_Z * sizeof(double * )); if(binghamDataPointer->dB2Bingham_Z==NULL){ binghamDataFree(binghamDataPointer); printf("fail to initiate bingham data space: menmory not enough!\n"); exit(1); } for(i=0;i<InterpNodesNumAxis_2D_Z;i++) binghamDataPointer->dB2Bingham_Z[i] = NULL; for(i=0;i<InterpNodesNumAxis_2D_Z;i++){ binghamDataPointer->dB2Bingham_Z[i] = (double*) malloc(InterpNodesNumAxis_2D_Z * sizeof(double)); if(binghamDataPointer->dB2Bingham_Z[i]==NULL){ binghamDataFree(binghamDataPointer); printf("fail to initiate bingham data space: menmory not enough!\n"); exit(1); } } for(i=0; i<InterpNodesNumAxis_2D_Z; i++){ fread(binghamDataPointer->dB2Bingham_Z[i], sizeof(double), InterpNodesNumAxis_2D_Z, fp); } binghamDataPointer->binghamVal_Z_x12 = (double **) malloc(InterpNodesNumAxis_2D_Z * sizeof(double * )); if(binghamDataPointer->binghamVal_Z_x12==NULL){ binghamDataFree(binghamDataPointer); printf("fail to initiate bingham data space: menmory not enough!\n"); exit(1); } for(i=0;i<InterpNodesNumAxis_2D_Z;i++) binghamDataPointer->binghamVal_Z_x12[i] = NULL; for(i=0;i<InterpNodesNumAxis_2D_Z;i++){ binghamDataPointer->binghamVal_Z_x12[i] = (double*) malloc(InterpNodesNumAxis_2D_Z * sizeof(double)); if(binghamDataPointer->binghamVal_Z_x12[i]==NULL){ binghamDataFree(binghamDataPointer); printf("fail to initiate bingham data space: menmory not enough!\n"); exit(1); } } for(i=0; i<InterpNodesNumAxis_2D_Z; i++){ fread(binghamDataPointer->binghamVal_Z_x12[i], sizeof(double), InterpNodesNumAxis_2D_Z, fp); } binghamDataPointer->dB1Bingham_Z_x12 = (double **) malloc(InterpNodesNumAxis_2D_Z * sizeof(double * )); if(binghamDataPointer->dB1Bingham_Z_x12==NULL){ binghamDataFree(binghamDataPointer); printf("fail to initiate bingham data space: menmory not enough!\n"); exit(1); } for(i=0;i<InterpNodesNumAxis_2D_Z;i++) binghamDataPointer->dB1Bingham_Z_x12[i] = NULL; for(i=0;i<InterpNodesNumAxis_2D_Z;i++){ binghamDataPointer->dB1Bingham_Z_x12[i] = (double*) malloc(InterpNodesNumAxis_2D_Z * sizeof(double)); if(binghamDataPointer->dB1Bingham_Z_x12[i]==NULL){ binghamDataFree(binghamDataPointer); printf("fail to initiate bingham data space: menmory not enough!\n"); exit(1); } } for(i=0; i<InterpNodesNumAxis_2D_Z; i++){ fread(binghamDataPointer->dB1Bingham_Z_x12[i], sizeof(double), InterpNodesNumAxis_2D_Z, fp); } binghamDataPointer->dB2Bingham_Z_x12 = (double **) malloc(InterpNodesNumAxis_2D_Z * sizeof(double * )); if(binghamDataPointer->dB2Bingham_Z_x12==NULL){ binghamDataFree(binghamDataPointer); printf("fail to initiate bingham data space: menmory not enough!\n"); exit(1); } for(i=0;i<InterpNodesNumAxis_2D_Z;i++) binghamDataPointer->dB2Bingham_Z_x12[i] = NULL; for(i=0;i<InterpNodesNumAxis_2D_Z;i++){ binghamDataPointer->dB2Bingham_Z_x12[i] = (double*) malloc(InterpNodesNumAxis_2D_Z * sizeof(double)); if(binghamDataPointer->dB2Bingham_Z_x12[i]==NULL){ binghamDataFree(binghamDataPointer); printf("fail to initiate bingham data space: menmory not enough!\n"); exit(1); } } for(i=0; i<InterpNodesNumAxis_2D_Z; i++){ fread(binghamDataPointer->dB2Bingham_Z_x12[i], sizeof(double), InterpNodesNumAxis_2D_Z, fp); } binghamDataPointer->binghamVal_Q_x14 = (double **) malloc(InterpNodesNumAxis_2D_Q * sizeof(double * )); if(binghamDataPointer->binghamVal_Q_x14==NULL){ binghamDataFree(binghamDataPointer); printf("fail to initiate bingham data space: menmory not enough!\n"); exit(1); } for(i=0;i<InterpNodesNumAxis_2D_Q;i++) binghamDataPointer->binghamVal_Q_x14[i] = NULL; for(i=0;i<InterpNodesNumAxis_2D_Q;i++){ binghamDataPointer->binghamVal_Q_x14[i] = (double*) malloc(InterpNodesNumAxis_2D_Q * sizeof(double)); if(binghamDataPointer->binghamVal_Q_x14[i]==NULL){ binghamDataFree(binghamDataPointer); printf("fail to initiate bingham data space: menmory not enough!\n"); exit(1); } } for(i=0; i<InterpNodesNumAxis_2D_Q; i++){ fread(binghamDataPointer->binghamVal_Q_x14[i], sizeof(double), InterpNodesNumAxis_2D_Q, fp); } binghamDataPointer->dB1Bingham_Q_x14 = (double **) malloc(InterpNodesNumAxis_2D_Q * sizeof(double * )); if(binghamDataPointer->dB1Bingham_Q_x14==NULL){ binghamDataFree(binghamDataPointer); printf("fail to initiate bingham data space: menmory not enough!\n"); exit(1); } for(i=0;i<InterpNodesNumAxis_2D_Q;i++) binghamDataPointer->dB1Bingham_Q_x14[i] = NULL; for(i=0;i<InterpNodesNumAxis_2D_Q;i++){ binghamDataPointer->dB1Bingham_Q_x14[i] = (double*) malloc(InterpNodesNumAxis_2D_Q * sizeof(double)); if(binghamDataPointer->dB1Bingham_Q_x14[i]==NULL){ binghamDataFree(binghamDataPointer); printf("fail to initiate bingham data space: menmory not enough!\n"); exit(1); } } for(i=0; i<InterpNodesNumAxis_2D_Q; i++){ fread(binghamDataPointer->dB1Bingham_Q_x14[i], sizeof(double), InterpNodesNumAxis_2D_Q, fp); } binghamDataPointer->dB2Bingham_Q_x14 = (double **) malloc(InterpNodesNumAxis_2D_Q * sizeof(double * )); if(binghamDataPointer->dB2Bingham_Q_x14==NULL){ binghamDataFree(binghamDataPointer); printf("fail to initiate bingham data space: menmory not enough!\n"); exit(1); } for(i=0;i<InterpNodesNumAxis_2D_Q;i++) binghamDataPointer->dB2Bingham_Q_x14[i] = NULL; for(i=0;i<InterpNodesNumAxis_2D_Q;i++){ binghamDataPointer->dB2Bingham_Q_x14[i] = (double*) malloc(InterpNodesNumAxis_2D_Q * sizeof(double)); if(binghamDataPointer->dB2Bingham_Q_x14[i]==NULL){ binghamDataFree(binghamDataPointer); printf("fail to initiate bingham data space: menmory not enough!\n"); exit(1); } } for(i=0; i<InterpNodesNumAxis_2D_Q; i++){ fread(binghamDataPointer->dB2Bingham_Q_x14[i], sizeof(double), InterpNodesNumAxis_2D_Q, fp); } binghamDataPointer->binghamVal_Q_x12x22 = (double **) malloc(InterpNodesNumAxis_2D_Q * sizeof(double * )); if(binghamDataPointer->binghamVal_Q_x12x22==NULL){ binghamDataFree(binghamDataPointer); printf("fail to initiate bingham data space: menmory not enough!\n"); exit(1); } for(i=0;i<InterpNodesNumAxis_2D_Q;i++) binghamDataPointer->binghamVal_Q_x12x22[i] = NULL; for(i=0;i<InterpNodesNumAxis_2D_Q;i++){ binghamDataPointer->binghamVal_Q_x12x22[i] = (double*) malloc(InterpNodesNumAxis_2D_Q * sizeof(double)); if(binghamDataPointer->binghamVal_Q_x12x22[i]==NULL){ binghamDataFree(binghamDataPointer); printf("fail to initiate bingham data space: menmory not enough!\n"); exit(1); } } for(i=0; i<InterpNodesNumAxis_2D_Q; i++){ fread(binghamDataPointer->binghamVal_Q_x12x22[i], sizeof(double), InterpNodesNumAxis_2D_Q, fp); } binghamDataPointer->dB1Bingham_Q_x12x22 = (double **) malloc(InterpNodesNumAxis_2D_Q * sizeof(double * )); if(binghamDataPointer->dB1Bingham_Q_x12x22==NULL){ binghamDataFree(binghamDataPointer); printf("fail to initiate bingham data space: menmory not enough!\n"); exit(1); } for(i=0;i<InterpNodesNumAxis_2D_Q;i++) binghamDataPointer->dB1Bingham_Q_x12x22[i] = NULL; for(i=0;i<InterpNodesNumAxis_2D_Q;i++){ binghamDataPointer->dB1Bingham_Q_x12x22[i] = (double*) malloc(InterpNodesNumAxis_2D_Q * sizeof(double)); if(binghamDataPointer->dB1Bingham_Q_x12x22[i]==NULL){ binghamDataFree(binghamDataPointer); printf("fail to initiate bingham data space: menmory not enough!\n"); exit(1); } } for(i=0; i<InterpNodesNumAxis_2D_Q; i++){ fread(binghamDataPointer->dB1Bingham_Q_x12x22[i], sizeof(double), InterpNodesNumAxis_2D_Q, fp); } binghamDataPointer->dB2Bingham_Q_x12x22 = (double **) malloc(InterpNodesNumAxis_2D_Q * sizeof(double * )); if(binghamDataPointer->dB2Bingham_Q_x12x22==NULL){ binghamDataFree(binghamDataPointer); printf("fail to initiate bingham data space: menmory not enough!\n"); exit(1); } for(i=0;i<InterpNodesNumAxis_2D_Q;i++) binghamDataPointer->dB2Bingham_Q_x12x22[i] = NULL; for(i=0;i<InterpNodesNumAxis_2D_Q;i++){ binghamDataPointer->dB2Bingham_Q_x12x22[i] = (double*) malloc(InterpNodesNumAxis_2D_Q * sizeof(double)); if(binghamDataPointer->dB2Bingham_Q_x12x22[i]==NULL){ binghamDataFree(binghamDataPointer); printf("fail to initiate bingham data space: menmory not enough!\n"); exit(1); } } for(i=0; i<InterpNodesNumAxis_2D_Q; i++){ fread(binghamDataPointer->dB2Bingham_Q_x12x22[i], sizeof(double), InterpNodesNumAxis_2D_Q, fp); } binghamDataPointer->finite1D_x0 = (double **) malloc(7 * sizeof(double * )); if(binghamDataPointer->finite1D_x0==NULL){ binghamDataFree(binghamDataPointer); printf("fail to initiate bingham data space: menmory not enough!\n"); exit(1); } for(i=0;i<7;i++) binghamDataPointer->finite1D_x0[i] = NULL; for(i=0;i<7;i++){ binghamDataPointer->finite1D_x0[i] = (double*) malloc(InterpNodesNumAxis_1D * sizeof(double)); if(binghamDataPointer->finite1D_x0[i]==NULL){ binghamDataFree(binghamDataPointer); printf("fail to initiate bingham data space: menmory not enough!\n"); exit(1); } } for(i=0; i<7; i++){ fread(binghamDataPointer->finite1D_x0[i], sizeof(double), InterpNodesNumAxis_1D, fp); } binghamDataPointer->finite1D_x2 = (double **) malloc(7 * sizeof(double * )); if(binghamDataPointer->finite1D_x2==NULL){ binghamDataFree(binghamDataPointer); printf("fail to initiate bingham data space: menmory not enough!\n"); exit(1); } for(i=0;i<7;i++) binghamDataPointer->finite1D_x2[i] = NULL; for(i=0;i<7;i++){ binghamDataPointer->finite1D_x2[i] = (double*) malloc(InterpNodesNumAxis_1D * sizeof(double)); if(binghamDataPointer->finite1D_x2[i]==NULL){ binghamDataFree(binghamDataPointer); printf("fail to initiate bingham data space: menmory not enough!\n"); exit(1); } } for(i=0; i<7; i++){ fread(binghamDataPointer->finite1D_x2[i], sizeof(double), InterpNodesNumAxis_1D, fp); } binghamDataPointer->finite1D_x4 = (double **) malloc(7 * sizeof(double * )); if(binghamDataPointer->finite1D_x4==NULL){ binghamDataFree(binghamDataPointer); printf("fail to initiate bingham data space: menmory not enough!\n"); exit(1); } for(i=0;i<7;i++) binghamDataPointer->finite1D_x4[i] = NULL; for(i=0;i<7;i++){ binghamDataPointer->finite1D_x4[i] = (double*) malloc(InterpNodesNumAxis_1D * sizeof(double)); if(binghamDataPointer->finite1D_x4[i]==NULL){ binghamDataFree(binghamDataPointer); printf("fail to initiate bingham data space: menmory not enough!\n"); exit(1); } } for(i=0; i<7; i++){ fread(binghamDataPointer->finite1D_x4[i], sizeof(double), InterpNodesNumAxis_1D, fp); } fclose(fp); return binghamDataPointer; } /* function for calculating the moments of Bingham distribution */ Moments bingham(double* b, binghamDataSpace* binghamDataPointer){ /* result variables */ double Z, Z_x12, Z_x22, Q_x12, Q_x22, Q_x14, Q_x24, Q_x12x22; /* a matrix for sorting the input array b and store its original order */ double sortMat[2][3]={{b[0], b[1], b[2]}, {1, 2, 3}}; /* a array stored the original order of b */ double BIndex[3]; /* sort the input array b in a increasing order and record its original order in BIndex */ sort(sortMat, 2); BIndex[0]=sortMat[1][0]; BIndex[1]=sortMat[1][1]; BIndex[2]=sortMat[1][2]; double b1=sortMat[0][0]; double b2=sortMat[0][1]; double b3=sortMat[0][2]; /* translate the array to make b3=0 */ double scale=exp(b3); b1=b1-b3; b2=b2-b3; b3=0; /* indexes of grid which the target point located in, in calculating the 2D interpolation in section 2.3 in the paper.*/ int indexB1, indexB2; /* Some denotes used in calculation to avoid repeated calculations */ double b1Cor, coCor, x1, x2; if(b1>Divide){ } else if(b2>Divide){ b1Cor=2*sqrt(-PI/b1); } else{ coCor=-2*PI/sqrt(b1*b2); x1=1/b1, x2=1/b2; } /* calculating Z */ /* calculating in case 2.3 in the paper. */ if(b1>Divide){ indexB1=-(int) (b1/AreaSpacing_Z); indexB2=-(int) (b2/AreaSpacing_Z); Z=hermiteInterpolate(AreaSpacing_Z, -indexB1*AreaSpacing_Z-AreaSpacing_Z, -indexB1*AreaSpacing_Z, -indexB2*AreaSpacing_Z-AreaSpacing_Z, -indexB2*AreaSpacing_Z, binghamDataPointer->binghamVal_Z[indexB2+1][indexB1+1], binghamDataPointer->binghamVal_Z[indexB2][indexB1+1], binghamDataPointer->binghamVal_Z[indexB2+1][indexB1], binghamDataPointer->binghamVal_Z[indexB2][indexB1], binghamDataPointer->dB1Bingham_Z[indexB2+1][indexB1+1], binghamDataPointer->dB1Bingham_Z[indexB2][indexB1+1], binghamDataPointer->dB1Bingham_Z[indexB2+1][indexB1], binghamDataPointer->dB1Bingham_Z[indexB2][indexB1], binghamDataPointer->dB2Bingham_Z[indexB2+1][indexB1+1], binghamDataPointer->dB2Bingham_Z[indexB2][indexB1+1], binghamDataPointer->dB2Bingham_Z[indexB2+1][indexB1], binghamDataPointer->dB2Bingham_Z[indexB2][indexB1], b1, b2); } /* calculating in case 2.2 in the paper. */ else if (b2>Divide){ Z=b1Cor*(calcDerivative(b2, 0, binghamDataPointer->finite1D_x0) - calcDerivative(b2, 2, binghamDataPointer->finite1D_x0)/4/b1 + calcDerivative(b2, 4, binghamDataPointer->finite1D_x0)/32/b1/b1 - calcDerivative(b2, 6, binghamDataPointer->finite1D_x0)/384/b1/b1/b1 + calcDerivative(b2, 8, binghamDataPointer->finite1D_x0)/6144/b1/b1/b1/b1 - calcDerivative(b2, 10, binghamDataPointer->finite1D_x0)/122880/b1/b1/b1/b1/b1 + calcDerivative(b2, 12, binghamDataPointer->finite1D_x0)/2949120/b1/b1/b1/b1/b1/b1); } /* calculating in case 2.1 in the paper. */ else { Z=coCor*(x1*(x1*(x1*(x1*(7.26745605469*x1 + 4.03747558594*x2 - 1.79443359375) + x2*(3.46069335938*x2 - 1.025390625) + 0.5859375) + x2*(x2*(3.46069335938*x2 - 0.9228515625) + 0.3515625) - 0.28125) + x2*(x2*(x2*(4.03747558594*x2 - 1.025390625) + 0.3515625) - 0.1875) + 0.25) + x2*(x2*(x2*(x2*(7.26745605469*x2 - 1.79443359375) + 0.5859375) - 0.28125) + 0.25) - 1.0); } /* calculating Z(x1^2) and Z(x1^2) */ /* calculating in case 2.3 in the paper. */ if(b1>Divide){ indexB1=-(int) (b1/AreaSpacing_Z); indexB2=-(int) (b2/AreaSpacing_Z); Z_x12=hermiteInterpolate(AreaSpacing_Z, -indexB1*AreaSpacing_Z-AreaSpacing_Z, -indexB1*AreaSpacing_Z, -indexB2*AreaSpacing_Z-AreaSpacing_Z, -indexB2*AreaSpacing_Z, binghamDataPointer->binghamVal_Z_x12[indexB2+1][indexB1+1], binghamDataPointer->binghamVal_Z_x12[indexB2][indexB1+1], binghamDataPointer->binghamVal_Z_x12[indexB2+1][indexB1], binghamDataPointer->binghamVal_Z_x12[indexB2][indexB1], binghamDataPointer->dB1Bingham_Z_x12[indexB2+1][indexB1+1], binghamDataPointer->dB1Bingham_Z_x12[indexB2][indexB1+1], binghamDataPointer->dB1Bingham_Z_x12[indexB2+1][indexB1], binghamDataPointer->dB1Bingham_Z_x12[indexB2][indexB1], binghamDataPointer->dB2Bingham_Z_x12[indexB2+1][indexB1+1], binghamDataPointer->dB2Bingham_Z_x12[indexB2][indexB1+1], binghamDataPointer->dB2Bingham_Z_x12[indexB2+1][indexB1], binghamDataPointer->dB2Bingham_Z_x12[indexB2][indexB1], b1, b2); Z_x22=hermiteInterpolate(AreaSpacing_Z, -indexB2*AreaSpacing_Z-AreaSpacing_Z, -indexB2*AreaSpacing_Z, -indexB1*AreaSpacing_Z-AreaSpacing_Z, -indexB1*AreaSpacing_Z, binghamDataPointer->binghamVal_Z_x12[indexB1+1][indexB2+1], binghamDataPointer->binghamVal_Z_x12[indexB1][indexB2+1], binghamDataPointer->binghamVal_Z_x12[indexB1+1][indexB2], binghamDataPointer->binghamVal_Z_x12[indexB1][indexB2], binghamDataPointer->dB1Bingham_Z_x12[indexB1+1][indexB2+1], binghamDataPointer->dB1Bingham_Z_x12[indexB1][indexB2+1], binghamDataPointer->dB1Bingham_Z_x12[indexB1+1][indexB2], binghamDataPointer->dB1Bingham_Z_x12[indexB1][indexB2], binghamDataPointer->dB2Bingham_Z_x12[indexB1+1][indexB2+1], binghamDataPointer->dB2Bingham_Z_x12[indexB1][indexB2+1], binghamDataPointer->dB2Bingham_Z_x12[indexB1+1][indexB2], binghamDataPointer->dB2Bingham_Z_x12[indexB1][indexB2], b2, b1); } /* calculating in case 2.2 in the paper. */ else if (b2>Divide){ Z_x12=b1Cor*(-calcDerivative(b2, 0, binghamDataPointer->finite1D_x0)/2/b1 + 0.375*calcDerivative(b2, 2, binghamDataPointer->finite1D_x0)/b1/b1 - 0.078125*calcDerivative(b2, 4, binghamDataPointer->finite1D_x0)/b1/b1/b1 + 0.00911458*calcDerivative(b2, 6, binghamDataPointer->finite1D_x0)/b1/b1/b1/b1 - 0.000732422*calcDerivative(b2, 8, binghamDataPointer->finite1D_x0)/b1/b1/b1/b1/b1 + 0.0000447591*calcDerivative(b2, 10, binghamDataPointer->finite1D_x0)/b1/b1/b1/b1/b1/b1); Z_x22=b1Cor*(calcDerivative(b2, 0, binghamDataPointer->finite1D_x2) - calcDerivative(b2, 2, binghamDataPointer->finite1D_x2)/4/b1 + calcDerivative(b2, 4, binghamDataPointer->finite1D_x2)/32/b1/b1 - calcDerivative(b2, 6, binghamDataPointer->finite1D_x2)/384/b1/b1/b1 + calcDerivative(b2, 8, binghamDataPointer->finite1D_x2)/6144/b1/b1/b1/b1 - calcDerivative(b2, 10, binghamDataPointer->finite1D_x2)/122880/b1/b1/b1/b1/b1 + calcDerivative(b2, 12, binghamDataPointer->finite1D_x2)/2949120/b1/b1/b1/b1/b1/b1); } /* calculating in case 2.1 in the paper. */ else { Z_x12=coCor*(-x1*(x1*(x1*(x1*(x1*(39.9710083008*x1 + 18.1686401367*x2 - 8.07495117188) + x2*(12.1124267578*x2 - 3.5888671875) + 2.05078125) + x2*(x2*(8.65173339844*x2 - 2.30712890625) + 0.87890625) - 0.703125) + x2*(x2*(x2*(6.05621337891*x2 - 1.5380859375) + 0.52734375) - 0.28125) + 0.375) + x2*(x2*(x2*(x2*(3.63372802734*x2 - 0.897216796875) + 0.29296875) - 0.140625) + 0.125) - 0.5)); Z_x22=coCor*(-x2*(x2*(x2*(x2*(x2*(39.9710083008*x2 + 18.1686401367*x1 - 8.07495117188) + x1*(12.1124267578*x1 - 3.5888671875) + 2.05078125) + x1*(x1*(8.65173339844*x1 - 2.30712890625) + 0.87890625) - 0.703125) + x1*(x1*(x1*(6.05621337891*x1 - 1.5380859375) + 0.52734375) - 0.28125) + 0.375) + x1*(x1*(x1*(x1*(3.63372802734*x1 - 0.897216796875) + 0.29296875) - 0.140625) + 0.125) - 0.5)); } /* calculating <x1^2> and <x2^2> */ Q_x12=Z_x12/Z; Q_x22=Z_x22/Z; /* calculating <x1^4> and <x2^4> */ /* calculating in case 2.3 in the paper. */ if(b1>Divide){ indexB1=-(int) (b1/AreaSpacing_Q); indexB2=-(int) (b2/AreaSpacing_Q); Q_x14=hermiteInterpolate(AreaSpacing_Q, -indexB1*AreaSpacing_Q-AreaSpacing_Q, -indexB1*AreaSpacing_Q, -indexB2*AreaSpacing_Q-AreaSpacing_Q, -indexB2*AreaSpacing_Q, binghamDataPointer->binghamVal_Q_x14[indexB2+1][indexB1+1], binghamDataPointer->binghamVal_Q_x14[indexB2][indexB1+1], binghamDataPointer->binghamVal_Q_x14[indexB2+1][indexB1], binghamDataPointer->binghamVal_Q_x14[indexB2][indexB1], binghamDataPointer->dB1Bingham_Q_x14[indexB2+1][indexB1+1], binghamDataPointer->dB1Bingham_Q_x14[indexB2][indexB1+1], binghamDataPointer->dB1Bingham_Q_x14[indexB2+1][indexB1], binghamDataPointer->dB1Bingham_Q_x14[indexB2][indexB1], binghamDataPointer->dB2Bingham_Q_x14[indexB2+1][indexB1+1], binghamDataPointer->dB2Bingham_Q_x14[indexB2][indexB1+1], binghamDataPointer->dB2Bingham_Q_x14[indexB2+1][indexB1], binghamDataPointer->dB2Bingham_Q_x14[indexB2][indexB1], b1, b2); Q_x24=hermiteInterpolate(AreaSpacing_Q, -indexB2*AreaSpacing_Q-AreaSpacing_Q, -indexB2*AreaSpacing_Q, -indexB1*AreaSpacing_Q-AreaSpacing_Q, -indexB1*AreaSpacing_Q, binghamDataPointer->binghamVal_Q_x14[indexB1+1][indexB2+1], binghamDataPointer->binghamVal_Q_x14[indexB1][indexB2+1], binghamDataPointer->binghamVal_Q_x14[indexB1+1][indexB2], binghamDataPointer->binghamVal_Q_x14[indexB1][indexB2], binghamDataPointer->dB1Bingham_Q_x14[indexB1+1][indexB2+1], binghamDataPointer->dB1Bingham_Q_x14[indexB1][indexB2+1], binghamDataPointer->dB1Bingham_Q_x14[indexB1+1][indexB2], binghamDataPointer->dB1Bingham_Q_x14[indexB1][indexB2], binghamDataPointer->dB2Bingham_Q_x14[indexB1+1][indexB2+1], binghamDataPointer->dB2Bingham_Q_x14[indexB1][indexB2+1], binghamDataPointer->dB2Bingham_Q_x14[indexB1+1][indexB2], binghamDataPointer->dB2Bingham_Q_x14[indexB1][indexB2], b2, b1); } /* calculating in case 2.2 in the paper. */ else if (b2>Divide){ Q_x14=b1Cor*(0.75*calcDerivative(b2, 0, binghamDataPointer->finite1D_x0)/b1/b1 - 0.9375*calcDerivative(b2, 2, binghamDataPointer->finite1D_x0)/b1/b1/b1 + 0.273438*calcDerivative(b2, 4, binghamDataPointer->finite1D_x0)/b1/b1/b1/b1 - 0.0410156*calcDerivative(b2, 6, binghamDataPointer->finite1D_x0)/b1/b1/b1/b1/b1 + 0.00402832*calcDerivative(b2, 8, binghamDataPointer->finite1D_x0)/b1/b1/b1/b1/b1/b1)/Z; Q_x24=b1Cor*(calcDerivative(b2, 0, binghamDataPointer->finite1D_x4) - calcDerivative(b2, 2, binghamDataPointer->finite1D_x4)/4/b1 + calcDerivative(b2, 4, binghamDataPointer->finite1D_x4)/32/b1/b1 - calcDerivative(b2, 6, binghamDataPointer->finite1D_x4)/384/b1/b1/b1 + calcDerivative(b2, 8, binghamDataPointer->finite1D_x4)/6144/b1/b1/b1/b1 - calcDerivative(b2, 10, binghamDataPointer->finite1D_x4)/122880/b1/b1/b1/b1/b1 + calcDerivative(b2, 12, binghamDataPointer->finite1D_x4)/2949120/b1/b1/b1/b1/b1/b1)/Z; } /* calculating in case 2.1 in the paper. */ else { Q_x14=coCor*(-x1*x1*(x1*(x1*(x1*(44.412231445312*x1 + 16.14990234375*x2 - 9.228515625) + x2*(8.074951171875*x2 - 3.076171875) + 2.4609375) + x2*(x2*(3.84521484375*x2 - 1.318359375) + 0.703125) - 0.9375) + x2*(x2*(x2*(1.3458251953125*x2 - 0.439453125) + 0.2109375) - 0.1875) + 0.75))/Z; Q_x24=coCor*(-x2*x2*(x2*(x2*(x2*(16.14990234375*x1 + 44.412231445312*x2 - 9.228515625) + x1*(8.074951171875*x1 - 3.076171875) + 2.4609375) + x1*(x1*(3.84521484375*x1 - 1.318359375) + 0.703125) - 0.9375) + x1*(x1*(x1*(1.3458251953125*x1 - 0.439453125) + 0.2109375) - 0.1875) + 0.75))/Z; } /* calculating <x1^2*x2^2> */ /* calculating in case 2.3 in the paper. */ if(b1>Divide){ indexB1=-(int) (b1/AreaSpacing_Q); indexB2=-(int) (b2/AreaSpacing_Q); Q_x12x22=hermiteInterpolate(AreaSpacing_Q, -indexB1*AreaSpacing_Q-AreaSpacing_Q, -indexB1*AreaSpacing_Q, -indexB2*AreaSpacing_Q-AreaSpacing_Q, -indexB2*AreaSpacing_Q, binghamDataPointer->binghamVal_Q_x12x22[indexB2+1][indexB1+1], binghamDataPointer->binghamVal_Q_x12x22[indexB2][indexB1+1], binghamDataPointer->binghamVal_Q_x12x22[indexB2+1][indexB1], binghamDataPointer->binghamVal_Q_x12x22[indexB2][indexB1], binghamDataPointer->dB1Bingham_Q_x12x22[indexB2+1][indexB1+1], binghamDataPointer->dB1Bingham_Q_x12x22[indexB2][indexB1+1], binghamDataPointer->dB1Bingham_Q_x12x22[indexB2+1][indexB1], binghamDataPointer->dB1Bingham_Q_x12x22[indexB2][indexB1], binghamDataPointer->dB2Bingham_Q_x12x22[indexB2+1][indexB1+1], binghamDataPointer->dB2Bingham_Q_x12x22[indexB2][indexB1+1], binghamDataPointer->dB2Bingham_Q_x12x22[indexB2+1][indexB1], binghamDataPointer->dB2Bingham_Q_x12x22[indexB2][indexB1], b1, b2); } /* calculating in case 2.2 in the paper. */ else if (b2>Divide){ Q_x12x22=b1Cor*(-calcDerivative(b2, 0, binghamDataPointer->finite1D_x2)/2/b1 + 0.375*calcDerivative(b2, 2, binghamDataPointer->finite1D_x2)/b1/b1 - 0.078125*calcDerivative(b2, 4, binghamDataPointer->finite1D_x2)/b1/b1/b1 + 0.00911458*calcDerivative(b2, 6, binghamDataPointer->finite1D_x2)/b1/b1/b1/b1 - 0.000732422*calcDerivative(b2, 8, binghamDataPointer->finite1D_x2)/b1/b1/b1/b1/b1 + 0.0000447591*calcDerivative(b2, 10, binghamDataPointer->finite1D_x2)/b1/b1/b1/b1/b1/b1)/Z; } /* calculating in case 2.1 in the paper. */ else { Q_x12x22=coCor*(-x1*(x1*(x1*(x2*(x2*(5.767822265625*x2 - 1.318359375) + 0.3515625) + x1*(4.0374755859375*x1*x2 + x2*(5.38330078125*x2 - 1.025390625))) + x2*(x2*(x2*(5.38330078125*x2 - 1.318359375) + 0.421875) - 0.1875)) + x2*(x2*(x2*(x2*(4.0374755859375*x2 - 1.025390625) + 0.3515625) - 0.1875) + 0.25)))/Z; } /* generate the moment functions corresponding to the original order of b */ Moments M; if(BIndex[0]==1 && BIndex[1]==2){ M.Q_x12x22=Q_x12x22; } else if(BIndex[0]==2 && BIndex[1]==1){ M.Q_x12x22=Q_x12x22; } else if(BIndex[0]==1 && BIndex[1]==3){ M.Q_x12x22=- Q_x14 - Q_x12x22 + Q_x12; } else if(BIndex[0]==3 && BIndex[1]==1){ M.Q_x12x22=- Q_x12x22 - Q_x24 + Q_x22; } else if(BIndex[0]==2 && BIndex[1]==3){ M.Q_x12x22=- Q_x14 - Q_x12x22 + Q_x12; } else if(BIndex[0]==3 && BIndex[1]==2){ M.Q_x12x22=- Q_x12x22 - Q_x24 + Q_x22; } double resortMat[4][3]={ {BIndex[0], BIndex[1], BIndex[2]}, {Z_x12, Z_x22, Z - Z_x12 - Z_x22}, {Q_x12, Q_x22, 1 - Q_x12 - Q_x22}, {Q_x14, Q_x24, Q_x14 + 2*Q_x12x22 - 2*Q_x12 + Q_x24 - 2*Q_x22 + 1}, }; sort(resortMat, 4); M.Z=scale*Z; M.Z_x12=scale*resortMat[1][0]; M.Z_x22=scale*resortMat[1][1]; M.Q_x12=resortMat[2][0]; M.Q_x22=resortMat[2][1]; M.Q_x14=resortMat[3][0]; M.Q_x24=resortMat[3][1]; return M; }
saltyfishie98/bike-alarm
onBike/lib/MotionSense/MotionSense.h
#ifndef BIKEALARM #define BIKEALARM #define test #include <Arduino.h> #include <Wire.h> #include <MPU6050.h> #define MPU_ADDR (0x68) class MotionSense { public: MotionSense(MPU6050* objectPtr) : objPtr(objectPtr) {} void begin_MPU6050(); void begin_MPU6050MotionSensor(); void runOnMotion(void (*onMotion)(void), void (*onStationary)(void)); private: const uint8_t regularCheck = 10; uint16_t data = 0; uint8_t confirmation = 0; MPU6050* objPtr; }; #endif
saltyfishie98/bike-alarm
library/LoRaComm/LoRaComm.h
<filename>library/LoRaComm/LoRaComm.h #ifndef LORA_COMM #define LORA_COMM #include <Arduino.h> #include <LoRa.h> enum class LORACOMM { TX, RX }; class LoRaComm { public: LoRaComm(LoRaClass* ObjAddr) : LoRaObj(ObjAddr) {} void begin(LORACOMM selection, bool overidePin = false, uint8_t overideNSS = 2, uint8_t overideRST = 1, uint8_t overideDIO0 = 0); void transmitChar(const char& message); void passCharRespondTo(char* respond); private: LoRaClass* LoRaObj; }; #endif
dagothar/apollo
src/hud.h
<reponame>dagothar/apollo #ifndef _HUD_H #define _HUD_H #include <iomanip> #include <GL/glut.h> #include "main.h" #include "control.h" #include "display.h" #include "simulink.h" #include "log.h" /*--------------------------------------------------------------- STALE ---------------------------------------------------------------*/ //wymiary slupkow const int bar_w = 20; //szerokosc slupka const int bar_h = 100; //wysokosc slupka //polozenie panelu informacji const int gui_iwin_x = 10; const int gui_iwin_y = 360; const int gui_iwin_w = 260; const int gui_iwin_h = 220; //polozenie panelu czasu const int gui_twin_x = 600; const int gui_twin_y = 570; const int gui_twin_w = 190; const int gui_twin_h = 20; //polozenie panelu parametrow const int gui_pwin_x = 10; const int gui_pwin_y = 10; const int gui_pwin_w = 260; const int gui_pwin_h = 185; //polozenie okna kamery dodatkowej const int gui_cwin_x = 605; const int gui_cwin_y = 10; const int gui_cwin_w = 185; const int gui_cwin_h = 185; //polozenie okna wiadomosci const int gui_mwin_x = 280; const int gui_mwin_y = 10; const int gui_mwin_w = 315; const int gui_mwin_h = 90; /*--------------------------------------------------------------- FUNKCJE ---------------------------------------------------------------*/ //wyswietla informacje w panelu //void Lander::draw_info(); //wyswietla hud w trybie fpp //void Lander::draw_hud(); #endif
dagothar/apollo
apollo/simulink/autopilot_rtwin/autopilot.h
/* * autopilot.h * * Real-Time Workshop code generation for Simulink model "autopilot.mdl". * * Model version : 1.184 * Real-Time Workshop version : 7.5 (R2010a) 25-Jan-2010 * C source code generated on : Tue Jul 19 19:43:27 2011 * * Target selection: rtwin.tlc * Note: GRT includes extra infrastructure and instrumentation for prototyping * Embedded hardware selection: Generic->32-bit x86 compatible * Code generation objectives: Unspecified * Validation result: Not run */ #ifndef RTW_HEADER_autopilot_h_ #define RTW_HEADER_autopilot_h_ #ifndef autopilot_COMMON_INCLUDES_ # define autopilot_COMMON_INCLUDES_ #include <string.h> #include "rtwtypes.h" #include "simstruc.h" #include "fixedpoint.h" #include "dt_info.h" #include "ext_work.h" #include "rtwintgt.h" #include "rt_nonfinite.h" #endif /* autopilot_COMMON_INCLUDES_ */ #include "autopilot_types.h" /* Macros for accessing real-time model data structure */ #ifndef rtmGetBlkStateChangeFlag # define rtmGetBlkStateChangeFlag(rtm) ((rtm)->ModelData.blkStateChange) #endif #ifndef rtmSetBlkStateChangeFlag # define rtmSetBlkStateChangeFlag(rtm, val) ((rtm)->ModelData.blkStateChange = (val)) #endif #ifndef rtmGetBlockIO # define rtmGetBlockIO(rtm) ((rtm)->ModelData.blockIO) #endif #ifndef rtmSetBlockIO # define rtmSetBlockIO(rtm, val) ((rtm)->ModelData.blockIO = (val)) #endif #ifndef rtmGetChecksums # define rtmGetChecksums(rtm) ((rtm)->Sizes.checksums) #endif #ifndef rtmSetChecksums # define rtmSetChecksums(rtm, val) ((rtm)->Sizes.checksums = (val)) #endif #ifndef rtmGetConstBlockIO # define rtmGetConstBlockIO(rtm) ((rtm)->ModelData.constBlockIO) #endif #ifndef rtmSetConstBlockIO # define rtmSetConstBlockIO(rtm, val) ((rtm)->ModelData.constBlockIO = (val)) #endif #ifndef rtmGetContStateDisabled # define rtmGetContStateDisabled(rtm) ((rtm)->ModelData.contStateDisabled) #endif #ifndef rtmSetContStateDisabled # define rtmSetContStateDisabled(rtm, val) ((rtm)->ModelData.contStateDisabled = (val)) #endif #ifndef rtmGetContStates # define rtmGetContStates(rtm) ((rtm)->ModelData.contStates) #endif #ifndef rtmSetContStates # define rtmSetContStates(rtm, val) ((rtm)->ModelData.contStates = (val)) #endif #ifndef rtmGetDataMapInfo # define rtmGetDataMapInfo(rtm) () #endif #ifndef rtmSetDataMapInfo # define rtmSetDataMapInfo(rtm, val) () #endif #ifndef rtmGetDefaultParam # define rtmGetDefaultParam(rtm) ((rtm)->ModelData.defaultParam) #endif #ifndef rtmSetDefaultParam # define rtmSetDefaultParam(rtm, val) ((rtm)->ModelData.defaultParam = (val)) #endif #ifndef rtmGetDerivCacheNeedsReset # define rtmGetDerivCacheNeedsReset(rtm) ((rtm)->ModelData.derivCacheNeedsReset) #endif #ifndef rtmSetDerivCacheNeedsReset # define rtmSetDerivCacheNeedsReset(rtm, val) ((rtm)->ModelData.derivCacheNeedsReset = (val)) #endif #ifndef rtmGetDirectFeedThrough # define rtmGetDirectFeedThrough(rtm) ((rtm)->Sizes.sysDirFeedThru) #endif #ifndef rtmSetDirectFeedThrough # define rtmSetDirectFeedThrough(rtm, val) ((rtm)->Sizes.sysDirFeedThru = (val)) #endif #ifndef rtmGetErrorStatusFlag # define rtmGetErrorStatusFlag(rtm) ((rtm)->errorStatus) #endif #ifndef rtmSetErrorStatusFlag # define rtmSetErrorStatusFlag(rtm, val) ((rtm)->errorStatus = (val)) #endif #ifndef rtmGetFinalTime # define rtmGetFinalTime(rtm) ((rtm)->Timing.tFinal) #endif #ifndef rtmSetFinalTime # define rtmSetFinalTime(rtm, val) ((rtm)->Timing.tFinal = (val)) #endif #ifndef rtmGetFirstInitCondFlag # define rtmGetFirstInitCondFlag(rtm) () #endif #ifndef rtmSetFirstInitCondFlag # define rtmSetFirstInitCondFlag(rtm, val) () #endif #ifndef rtmGetIntgData # define rtmGetIntgData(rtm) ((rtm)->ModelData.intgData) #endif #ifndef rtmSetIntgData # define rtmSetIntgData(rtm, val) ((rtm)->ModelData.intgData = (val)) #endif #ifndef rtmGetMdlRefGlobalTID # define rtmGetMdlRefGlobalTID(rtm) () #endif #ifndef rtmSetMdlRefGlobalTID # define rtmSetMdlRefGlobalTID(rtm, val) () #endif #ifndef rtmGetMdlRefTriggerTID # define rtmGetMdlRefTriggerTID(rtm) () #endif #ifndef rtmSetMdlRefTriggerTID # define rtmSetMdlRefTriggerTID(rtm, val) () #endif #ifndef rtmGetModelMappingInfo # define rtmGetModelMappingInfo(rtm) ((rtm)->SpecialInfo.mappingInfo) #endif #ifndef rtmSetModelMappingInfo # define rtmSetModelMappingInfo(rtm, val) ((rtm)->SpecialInfo.mappingInfo = (val)) #endif #ifndef rtmGetModelName # define rtmGetModelName(rtm) ((rtm)->modelName) #endif #ifndef rtmSetModelName # define rtmSetModelName(rtm, val) ((rtm)->modelName = (val)) #endif #ifndef rtmGetNonInlinedSFcns # define rtmGetNonInlinedSFcns(rtm) () #endif #ifndef rtmSetNonInlinedSFcns # define rtmSetNonInlinedSFcns(rtm, val) () #endif #ifndef rtmGetNumBlockIO # define rtmGetNumBlockIO(rtm) ((rtm)->Sizes.numBlockIO) #endif #ifndef rtmSetNumBlockIO # define rtmSetNumBlockIO(rtm, val) ((rtm)->Sizes.numBlockIO = (val)) #endif #ifndef rtmGetNumBlockParams # define rtmGetNumBlockParams(rtm) ((rtm)->Sizes.numBlockPrms) #endif #ifndef rtmSetNumBlockParams # define rtmSetNumBlockParams(rtm, val) ((rtm)->Sizes.numBlockPrms = (val)) #endif #ifndef rtmGetNumBlocks # define rtmGetNumBlocks(rtm) ((rtm)->Sizes.numBlocks) #endif #ifndef rtmSetNumBlocks # define rtmSetNumBlocks(rtm, val) ((rtm)->Sizes.numBlocks = (val)) #endif #ifndef rtmGetNumContStates # define rtmGetNumContStates(rtm) ((rtm)->Sizes.numContStates) #endif #ifndef rtmSetNumContStates # define rtmSetNumContStates(rtm, val) ((rtm)->Sizes.numContStates = (val)) #endif #ifndef rtmGetNumDWork # define rtmGetNumDWork(rtm) ((rtm)->Sizes.numDwork) #endif #ifndef rtmSetNumDWork # define rtmSetNumDWork(rtm, val) ((rtm)->Sizes.numDwork = (val)) #endif #ifndef rtmGetNumInputPorts # define rtmGetNumInputPorts(rtm) ((rtm)->Sizes.numIports) #endif #ifndef rtmSetNumInputPorts # define rtmSetNumInputPorts(rtm, val) ((rtm)->Sizes.numIports = (val)) #endif #ifndef rtmGetNumNonSampledZCs # define rtmGetNumNonSampledZCs(rtm) ((rtm)->Sizes.numNonSampZCs) #endif #ifndef rtmSetNumNonSampledZCs # define rtmSetNumNonSampledZCs(rtm, val) ((rtm)->Sizes.numNonSampZCs = (val)) #endif #ifndef rtmGetNumOutputPorts # define rtmGetNumOutputPorts(rtm) ((rtm)->Sizes.numOports) #endif #ifndef rtmSetNumOutputPorts # define rtmSetNumOutputPorts(rtm, val) ((rtm)->Sizes.numOports = (val)) #endif #ifndef rtmGetNumSFcnParams # define rtmGetNumSFcnParams(rtm) ((rtm)->Sizes.numSFcnPrms) #endif #ifndef rtmSetNumSFcnParams # define rtmSetNumSFcnParams(rtm, val) ((rtm)->Sizes.numSFcnPrms = (val)) #endif #ifndef rtmGetNumSFunctions # define rtmGetNumSFunctions(rtm) ((rtm)->Sizes.numSFcns) #endif #ifndef rtmSetNumSFunctions # define rtmSetNumSFunctions(rtm, val) ((rtm)->Sizes.numSFcns = (val)) #endif #ifndef rtmGetNumSampleTimes # define rtmGetNumSampleTimes(rtm) ((rtm)->Sizes.numSampTimes) #endif #ifndef rtmSetNumSampleTimes # define rtmSetNumSampleTimes(rtm, val) ((rtm)->Sizes.numSampTimes = (val)) #endif #ifndef rtmGetNumU # define rtmGetNumU(rtm) ((rtm)->Sizes.numU) #endif #ifndef rtmSetNumU # define rtmSetNumU(rtm, val) ((rtm)->Sizes.numU = (val)) #endif #ifndef rtmGetNumY # define rtmGetNumY(rtm) ((rtm)->Sizes.numY) #endif #ifndef rtmSetNumY # define rtmSetNumY(rtm, val) ((rtm)->Sizes.numY = (val)) #endif #ifndef rtmGetOdeF # define rtmGetOdeF(rtm) ((rtm)->ModelData.odeF) #endif #ifndef rtmSetOdeF # define rtmSetOdeF(rtm, val) ((rtm)->ModelData.odeF = (val)) #endif #ifndef rtmGetOdeY # define rtmGetOdeY(rtm) () #endif #ifndef rtmSetOdeY # define rtmSetOdeY(rtm, val) () #endif #ifndef rtmGetOffsetTimeArray # define rtmGetOffsetTimeArray(rtm) ((rtm)->Timing.offsetTimesArray) #endif #ifndef rtmSetOffsetTimeArray # define rtmSetOffsetTimeArray(rtm, val) ((rtm)->Timing.offsetTimesArray = (val)) #endif #ifndef rtmGetOffsetTimePtr # define rtmGetOffsetTimePtr(rtm) ((rtm)->Timing.offsetTimes) #endif #ifndef rtmSetOffsetTimePtr # define rtmSetOffsetTimePtr(rtm, val) ((rtm)->Timing.offsetTimes = (val)) #endif #ifndef rtmGetOptions # define rtmGetOptions(rtm) ((rtm)->Sizes.options) #endif #ifndef rtmSetOptions # define rtmSetOptions(rtm, val) ((rtm)->Sizes.options = (val)) #endif #ifndef rtmGetParamIsMalloced # define rtmGetParamIsMalloced(rtm) () #endif #ifndef rtmSetParamIsMalloced # define rtmSetParamIsMalloced(rtm, val) () #endif #ifndef rtmGetPath # define rtmGetPath(rtm) ((rtm)->path) #endif #ifndef rtmSetPath # define rtmSetPath(rtm, val) ((rtm)->path = (val)) #endif #ifndef rtmGetPerTaskSampleHits # define rtmGetPerTaskSampleHits(rtm) () #endif #ifndef rtmSetPerTaskSampleHits # define rtmSetPerTaskSampleHits(rtm, val) () #endif #ifndef rtmGetPerTaskSampleHitsArray # define rtmGetPerTaskSampleHitsArray(rtm) ((rtm)->Timing.perTaskSampleHitsArray) #endif #ifndef rtmSetPerTaskSampleHitsArray # define rtmSetPerTaskSampleHitsArray(rtm, val) ((rtm)->Timing.perTaskSampleHitsArray = (val)) #endif #ifndef rtmGetPerTaskSampleHitsPtr # define rtmGetPerTaskSampleHitsPtr(rtm) ((rtm)->Timing.perTaskSampleHits) #endif #ifndef rtmSetPerTaskSampleHitsPtr # define rtmSetPerTaskSampleHitsPtr(rtm, val) ((rtm)->Timing.perTaskSampleHits = (val)) #endif #ifndef rtmGetPrevZCSigState # define rtmGetPrevZCSigState(rtm) ((rtm)->ModelData.prevZCSigState) #endif #ifndef rtmSetPrevZCSigState # define rtmSetPrevZCSigState(rtm, val) ((rtm)->ModelData.prevZCSigState = (val)) #endif #ifndef rtmGetRTWExtModeInfo # define rtmGetRTWExtModeInfo(rtm) ((rtm)->extModeInfo) #endif #ifndef rtmSetRTWExtModeInfo # define rtmSetRTWExtModeInfo(rtm, val) ((rtm)->extModeInfo = (val)) #endif #ifndef rtmGetRTWGeneratedSFcn # define rtmGetRTWGeneratedSFcn(rtm) ((rtm)->Sizes.rtwGenSfcn) #endif #ifndef rtmSetRTWGeneratedSFcn # define rtmSetRTWGeneratedSFcn(rtm, val) ((rtm)->Sizes.rtwGenSfcn = (val)) #endif #ifndef rtmGetRTWLogInfo # define rtmGetRTWLogInfo(rtm) () #endif #ifndef rtmSetRTWLogInfo # define rtmSetRTWLogInfo(rtm, val) () #endif #ifndef rtmGetRTWRTModelMethodsInfo # define rtmGetRTWRTModelMethodsInfo(rtm) () #endif #ifndef rtmSetRTWRTModelMethodsInfo # define rtmSetRTWRTModelMethodsInfo(rtm, val) () #endif #ifndef rtmGetRTWSfcnInfo # define rtmGetRTWSfcnInfo(rtm) ((rtm)->sfcnInfo) #endif #ifndef rtmSetRTWSfcnInfo # define rtmSetRTWSfcnInfo(rtm, val) ((rtm)->sfcnInfo = (val)) #endif #ifndef rtmGetRTWSolverInfo # define rtmGetRTWSolverInfo(rtm) ((rtm)->solverInfo) #endif #ifndef rtmSetRTWSolverInfo # define rtmSetRTWSolverInfo(rtm, val) ((rtm)->solverInfo = (val)) #endif #ifndef rtmGetRTWSolverInfoPtr # define rtmGetRTWSolverInfoPtr(rtm) ((rtm)->solverInfoPtr) #endif #ifndef rtmSetRTWSolverInfoPtr # define rtmSetRTWSolverInfoPtr(rtm, val) ((rtm)->solverInfoPtr = (val)) #endif #ifndef rtmGetReservedForXPC # define rtmGetReservedForXPC(rtm) ((rtm)->SpecialInfo.xpcData) #endif #ifndef rtmSetReservedForXPC # define rtmSetReservedForXPC(rtm, val) ((rtm)->SpecialInfo.xpcData = (val)) #endif #ifndef rtmGetRootDWork # define rtmGetRootDWork(rtm) ((rtm)->Work.dwork) #endif #ifndef rtmSetRootDWork # define rtmSetRootDWork(rtm, val) ((rtm)->Work.dwork = (val)) #endif #ifndef rtmGetSFunctions # define rtmGetSFunctions(rtm) ((rtm)->childSfunctions) #endif #ifndef rtmSetSFunctions # define rtmSetSFunctions(rtm, val) ((rtm)->childSfunctions = (val)) #endif #ifndef rtmGetSampleHitArray # define rtmGetSampleHitArray(rtm) ((rtm)->Timing.sampleHitArray) #endif #ifndef rtmSetSampleHitArray # define rtmSetSampleHitArray(rtm, val) ((rtm)->Timing.sampleHitArray = (val)) #endif #ifndef rtmGetSampleHitPtr # define rtmGetSampleHitPtr(rtm) ((rtm)->Timing.sampleHits) #endif #ifndef rtmSetSampleHitPtr # define rtmSetSampleHitPtr(rtm, val) ((rtm)->Timing.sampleHits = (val)) #endif #ifndef rtmGetSampleTimeArray # define rtmGetSampleTimeArray(rtm) ((rtm)->Timing.sampleTimesArray) #endif #ifndef rtmSetSampleTimeArray # define rtmSetSampleTimeArray(rtm, val) ((rtm)->Timing.sampleTimesArray = (val)) #endif #ifndef rtmGetSampleTimePtr # define rtmGetSampleTimePtr(rtm) ((rtm)->Timing.sampleTimes) #endif #ifndef rtmSetSampleTimePtr # define rtmSetSampleTimePtr(rtm, val) ((rtm)->Timing.sampleTimes = (val)) #endif #ifndef rtmGetSampleTimeTaskIDArray # define rtmGetSampleTimeTaskIDArray(rtm) ((rtm)->Timing.sampleTimeTaskIDArray) #endif #ifndef rtmSetSampleTimeTaskIDArray # define rtmSetSampleTimeTaskIDArray(rtm, val) ((rtm)->Timing.sampleTimeTaskIDArray = (val)) #endif #ifndef rtmGetSampleTimeTaskIDPtr # define rtmGetSampleTimeTaskIDPtr(rtm) ((rtm)->Timing.sampleTimeTaskIDPtr) #endif #ifndef rtmSetSampleTimeTaskIDPtr # define rtmSetSampleTimeTaskIDPtr(rtm, val) ((rtm)->Timing.sampleTimeTaskIDPtr = (val)) #endif #ifndef rtmGetSimMode # define rtmGetSimMode(rtm) ((rtm)->simMode) #endif #ifndef rtmSetSimMode # define rtmSetSimMode(rtm, val) ((rtm)->simMode = (val)) #endif #ifndef rtmGetSimTimeStep # define rtmGetSimTimeStep(rtm) ((rtm)->Timing.simTimeStep) #endif #ifndef rtmSetSimTimeStep # define rtmSetSimTimeStep(rtm, val) ((rtm)->Timing.simTimeStep = (val)) #endif #ifndef rtmGetStartTime # define rtmGetStartTime(rtm) ((rtm)->Timing.tStart) #endif #ifndef rtmSetStartTime # define rtmSetStartTime(rtm, val) ((rtm)->Timing.tStart = (val)) #endif #ifndef rtmGetStepSize # define rtmGetStepSize(rtm) ((rtm)->Timing.stepSize) #endif #ifndef rtmSetStepSize # define rtmSetStepSize(rtm, val) ((rtm)->Timing.stepSize = (val)) #endif #ifndef rtmGetStopRequestedFlag # define rtmGetStopRequestedFlag(rtm) ((rtm)->Timing.stopRequestedFlag) #endif #ifndef rtmSetStopRequestedFlag # define rtmSetStopRequestedFlag(rtm, val) ((rtm)->Timing.stopRequestedFlag = (val)) #endif #ifndef rtmGetTaskCounters # define rtmGetTaskCounters(rtm) () #endif #ifndef rtmSetTaskCounters # define rtmSetTaskCounters(rtm, val) () #endif #ifndef rtmGetTaskTimeArray # define rtmGetTaskTimeArray(rtm) ((rtm)->Timing.tArray) #endif #ifndef rtmSetTaskTimeArray # define rtmSetTaskTimeArray(rtm, val) ((rtm)->Timing.tArray = (val)) #endif #ifndef rtmGetTimePtr # define rtmGetTimePtr(rtm) ((rtm)->Timing.t) #endif #ifndef rtmSetTimePtr # define rtmSetTimePtr(rtm, val) ((rtm)->Timing.t = (val)) #endif #ifndef rtmGetTimingData # define rtmGetTimingData(rtm) ((rtm)->Timing.timingData) #endif #ifndef rtmSetTimingData # define rtmSetTimingData(rtm, val) ((rtm)->Timing.timingData = (val)) #endif #ifndef rtmGetU # define rtmGetU(rtm) ((rtm)->ModelData.inputs) #endif #ifndef rtmSetU # define rtmSetU(rtm, val) ((rtm)->ModelData.inputs = (val)) #endif #ifndef rtmGetVarNextHitTimesListPtr # define rtmGetVarNextHitTimesListPtr(rtm) ((rtm)->Timing.varNextHitTimesList) #endif #ifndef rtmSetVarNextHitTimesListPtr # define rtmSetVarNextHitTimesListPtr(rtm, val) ((rtm)->Timing.varNextHitTimesList = (val)) #endif #ifndef rtmGetY # define rtmGetY(rtm) ((rtm)->ModelData.outputs) #endif #ifndef rtmSetY # define rtmSetY(rtm, val) ((rtm)->ModelData.outputs = (val)) #endif #ifndef rtmGetZCCacheNeedsReset # define rtmGetZCCacheNeedsReset(rtm) ((rtm)->ModelData.zCCacheNeedsReset) #endif #ifndef rtmSetZCCacheNeedsReset # define rtmSetZCCacheNeedsReset(rtm, val) ((rtm)->ModelData.zCCacheNeedsReset = (val)) #endif #ifndef rtmGetZCSignalValues # define rtmGetZCSignalValues(rtm) ((rtm)->ModelData.zcSignalValues) #endif #ifndef rtmSetZCSignalValues # define rtmSetZCSignalValues(rtm, val) ((rtm)->ModelData.zcSignalValues = (val)) #endif #ifndef rtmGet_TimeOfLastOutput # define rtmGet_TimeOfLastOutput(rtm) ((rtm)->Timing.timeOfLastOutput) #endif #ifndef rtmSet_TimeOfLastOutput # define rtmSet_TimeOfLastOutput(rtm, val) ((rtm)->Timing.timeOfLastOutput = (val)) #endif #ifndef rtmGetdX # define rtmGetdX(rtm) ((rtm)->ModelData.derivs) #endif #ifndef rtmSetdX # define rtmSetdX(rtm, val) ((rtm)->ModelData.derivs = (val)) #endif #ifndef rtmGetChecksumVal # define rtmGetChecksumVal(rtm, idx) ((rtm)->Sizes.checksums[idx]) #endif #ifndef rtmSetChecksumVal # define rtmSetChecksumVal(rtm, idx, val) ((rtm)->Sizes.checksums[idx] = (val)) #endif #ifndef rtmGetDWork # define rtmGetDWork(rtm, idx) ((rtm)->Work.dwork[idx]) #endif #ifndef rtmSetDWork # define rtmSetDWork(rtm, idx, val) ((rtm)->Work.dwork[idx] = (val)) #endif #ifndef rtmGetOffsetTime # define rtmGetOffsetTime(rtm, idx) ((rtm)->Timing.offsetTimes[idx]) #endif #ifndef rtmSetOffsetTime # define rtmSetOffsetTime(rtm, idx, val) ((rtm)->Timing.offsetTimes[idx] = (val)) #endif #ifndef rtmGetSFunction # define rtmGetSFunction(rtm, idx) ((rtm)->childSfunctions[idx]) #endif #ifndef rtmSetSFunction # define rtmSetSFunction(rtm, idx, val) ((rtm)->childSfunctions[idx] = (val)) #endif #ifndef rtmGetSampleTime # define rtmGetSampleTime(rtm, idx) ((rtm)->Timing.sampleTimes[idx]) #endif #ifndef rtmSetSampleTime # define rtmSetSampleTime(rtm, idx, val) ((rtm)->Timing.sampleTimes[idx] = (val)) #endif #ifndef rtmGetSampleTimeTaskID # define rtmGetSampleTimeTaskID(rtm, idx) ((rtm)->Timing.sampleTimeTaskIDPtr[idx]) #endif #ifndef rtmSetSampleTimeTaskID # define rtmSetSampleTimeTaskID(rtm, idx, val) ((rtm)->Timing.sampleTimeTaskIDPtr[idx] = (val)) #endif #ifndef rtmGetVarNextHitTime # define rtmGetVarNextHitTime(rtm, idx) ((rtm)->Timing.varNextHitTimesList[idx]) #endif #ifndef rtmSetVarNextHitTime # define rtmSetVarNextHitTime(rtm, idx, val) ((rtm)->Timing.varNextHitTimesList[idx] = (val)) #endif #ifndef rtmIsContinuousTask # define rtmIsContinuousTask(rtm, tid) ((tid) == 0) #endif #ifndef rtmGetErrorStatus # define rtmGetErrorStatus(rtm) ((rtm)->errorStatus) #endif #ifndef rtmSetErrorStatus # define rtmSetErrorStatus(rtm, val) ((rtm)->errorStatus = (val)) #endif #ifndef rtmIsMajorTimeStep # define rtmIsMajorTimeStep(rtm) (((rtm)->Timing.simTimeStep) == MAJOR_TIME_STEP) #endif #ifndef rtmIsMinorTimeStep # define rtmIsMinorTimeStep(rtm) (((rtm)->Timing.simTimeStep) == MINOR_TIME_STEP) #endif #ifndef rtmIsSampleHit # define rtmIsSampleHit(rtm, sti, tid) ((rtmIsMajorTimeStep((rtm)) && (rtm)->Timing.sampleHits[(rtm)->Timing.sampleTimeTaskIDPtr[sti]])) #endif #ifndef rtmGetStopRequested # define rtmGetStopRequested(rtm) ((rtm)->Timing.stopRequestedFlag) #endif #ifndef rtmSetStopRequested # define rtmSetStopRequested(rtm, val) ((rtm)->Timing.stopRequestedFlag = (val)) #endif #ifndef rtmGetStopRequestedPtr # define rtmGetStopRequestedPtr(rtm) (&((rtm)->Timing.stopRequestedFlag)) #endif #ifndef rtmGetT # define rtmGetT(rtm) (rtmGetTPtr((rtm))[0]) #endif #ifndef rtmSetT # define rtmSetT(rtm, val) /* Do Nothing */ #endif #ifndef rtmGetTFinal # define rtmGetTFinal(rtm) ((rtm)->Timing.tFinal) #endif #ifndef rtmSetTFinal # define rtmSetTFinal(rtm, val) ((rtm)->Timing.tFinal = (val)) #endif #ifndef rtmGetTPtr # define rtmGetTPtr(rtm) ((rtm)->Timing.t) #endif #ifndef rtmSetTPtr # define rtmSetTPtr(rtm, val) ((rtm)->Timing.t = (val)) #endif #ifndef rtmGetTStart # define rtmGetTStart(rtm) ((rtm)->Timing.tStart) #endif #ifndef rtmSetTStart # define rtmSetTStart(rtm, val) ((rtm)->Timing.tStart = (val)) #endif #ifndef rtmGetTaskTime # define rtmGetTaskTime(rtm, sti) (rtmGetTPtr((rtm))[(rtm)->Timing.sampleTimeTaskIDPtr[sti]]) #endif #ifndef rtmSetTaskTime # define rtmSetTaskTime(rtm, sti, val) (rtmGetTPtr((rtm))[sti] = (val)) #endif #ifndef rtmGetTimeOfLastOutput # define rtmGetTimeOfLastOutput(rtm) ((rtm)->Timing.timeOfLastOutput) #endif #ifdef rtmGetRTWSolverInfo #undef rtmGetRTWSolverInfo #endif #define rtmGetRTWSolverInfo(rtm) &((rtm)->solverInfo) /* Definition for use in the target main file */ #define autopilot_rtModel RT_MODEL_autopilot /* Block signals (auto storage) */ typedef struct { real_T PacketInput_o3[2]; /* '<S1>/Packet Input' */ real_T PacketInput_o4[7]; /* '<S1>/Packet Input' */ real_T PacketInput_o5[6]; /* '<S1>/Packet Input' */ real_T PacketInput_o6[8]; /* '<S1>/Packet Input' */ real_T RateTransition3[2]; /* '<S1>/Rate Transition3' */ real_T RateTransition4[7]; /* '<S1>/Rate Transition4' */ real_T RateTransition5[6]; /* '<S1>/Rate Transition5' */ real_T RateTransition6[8]; /* '<S1>/Rate Transition6' */ real_T DataTypeConversion; /* '<S3>/Data Type Conversion' */ real_T DerivativeGain; /* '<S7>/Derivative Gain' */ real_T FilterCoefficient; /* '<S7>/Filter Coefficient' */ real_T IntegralGain; /* '<S7>/Integral Gain' */ real_T ProportionalGain; /* '<S7>/Proportional Gain' */ real_T Switch; /* '<S3>/Switch' */ real_T DataTypeConversion_o; /* '<S4>/Data Type Conversion' */ real_T DerivativeGain_e; /* '<S8>/Derivative Gain' */ real_T FilterCoefficient_f; /* '<S8>/Filter Coefficient' */ real_T IntegralGain_k; /* '<S8>/Integral Gain' */ real_T ProportionalGain_i; /* '<S8>/Proportional Gain' */ real_T Switch_l; /* '<S4>/Switch' */ real_T Sum; /* '<S5>/Sum' */ real_T DataTypeConversion_c; /* '<S5>/Data Type Conversion' */ real_T DerivativeGain_i; /* '<S9>/Derivative Gain' */ real_T FilterCoefficient_c; /* '<S9>/Filter Coefficient' */ real_T IntegralGain_a; /* '<S9>/Integral Gain' */ real_T ProportionalGain_o; /* '<S9>/Proportional Gain' */ real_T Switch_i; /* '<S5>/Switch' */ real_T DataTypeConversion_l; /* '<S6>/Data Type Conversion' */ real_T DerivativeGain_ei; /* '<S10>/Derivative Gain' */ real_T FilterCoefficient_e; /* '<S10>/Filter Coefficient' */ real_T IntegralGain_m; /* '<S10>/Integral Gain' */ real_T ProportionalGain_l; /* '<S10>/Proportional Gain' */ real_T Switch_e; /* '<S6>/Switch' */ int32_T PacketInput_o1; /* '<S1>/Packet Input' */ int32_T PacketInput_o2; /* '<S1>/Packet Input' */ int32_T RateTransition2; /* '<S1>/Rate Transition2' */ boolean_T LogicalOperator; /* '<S3>/Logical Operator' */ boolean_T LogicalOperator_n; /* '<S4>/Logical Operator' */ boolean_T LogicalOperator_i; /* '<S5>/Logical Operator' */ boolean_T LogicalOperator_d; /* '<S6>/Logical Operator' */ } BlockIO_autopilot; /* Block states (auto storage) for system '<Root>' */ typedef struct { struct { void *LoggedData; } Scope_PWORK; /* '<Root>/Scope' */ } D_Work_autopilot; /* Continuous states (auto storage) */ typedef struct { real_T Filter_CSTATE; /* '<S7>/Filter' */ real_T Integrator_CSTATE; /* '<S7>/Integrator' */ real_T Filter_CSTATE_l; /* '<S8>/Filter' */ real_T Integrator_CSTATE_d; /* '<S8>/Integrator' */ real_T Filter_CSTATE_i; /* '<S9>/Filter' */ real_T Integrator_CSTATE_e; /* '<S9>/Integrator' */ real_T Filter_CSTATE_p; /* '<S10>/Filter' */ real_T Integrator_CSTATE_n; /* '<S10>/Integrator' */ } ContinuousStates_autopilot; /* State derivatives (auto storage) */ typedef struct { real_T Filter_CSTATE; /* '<S7>/Filter' */ real_T Integrator_CSTATE; /* '<S7>/Integrator' */ real_T Filter_CSTATE_l; /* '<S8>/Filter' */ real_T Integrator_CSTATE_d; /* '<S8>/Integrator' */ real_T Filter_CSTATE_i; /* '<S9>/Filter' */ real_T Integrator_CSTATE_e; /* '<S9>/Integrator' */ real_T Filter_CSTATE_p; /* '<S10>/Filter' */ real_T Integrator_CSTATE_n; /* '<S10>/Integrator' */ } StateDerivatives_autopilot; /* State disabled */ typedef struct { boolean_T Filter_CSTATE; /* '<S7>/Filter' */ boolean_T Integrator_CSTATE; /* '<S7>/Integrator' */ boolean_T Filter_CSTATE_l; /* '<S8>/Filter' */ boolean_T Integrator_CSTATE_d; /* '<S8>/Integrator' */ boolean_T Filter_CSTATE_i; /* '<S9>/Filter' */ boolean_T Integrator_CSTATE_e; /* '<S9>/Integrator' */ boolean_T Filter_CSTATE_p; /* '<S10>/Filter' */ boolean_T Integrator_CSTATE_n; /* '<S10>/Integrator' */ } StateDisabled_autopilot; /* Zero-crossing (trigger) state */ typedef struct { ZCSigState Filter_Reset_ZCE; /* '<S7>/Filter' */ ZCSigState Integrator_Reset_ZCE; /* '<S7>/Integrator' */ ZCSigState Filter_Reset_ZCE_k; /* '<S8>/Filter' */ ZCSigState Integrator_Reset_ZCE_k; /* '<S8>/Integrator' */ ZCSigState Filter_Reset_ZCE_a; /* '<S9>/Filter' */ ZCSigState Integrator_Reset_ZCE_h; /* '<S9>/Integrator' */ ZCSigState Filter_Reset_ZCE_b; /* '<S10>/Filter' */ ZCSigState Integrator_Reset_ZCE_j; /* '<S10>/Integrator' */ } PrevZCSigStates_autopilot; #ifndef ODE1_INTG #define ODE1_INTG /* ODE1 Integration Data */ typedef struct { real_T *f[1]; /* derivatives */ } ODE1_IntgData; #endif /* Backward compatible GRT Identifiers */ #define rtB autopilot_B #define BlockIO BlockIO_autopilot #define rtX autopilot_X #define ContinuousStates ContinuousStates_autopilot #define rtP autopilot_P #define Parameters Parameters_autopilot #define rtDWork autopilot_DWork #define D_Work D_Work_autopilot #define rtPrevZCSigState autopilot_PrevZCSigState #define PrevZCSigStates PrevZCSigStates_autopilot /* Parameters (auto storage) */ struct Parameters_autopilot_ { real_T DerivativeGain_Gain; /* Expression: D * Referenced by: '<S7>/Derivative Gain' */ real_T Filter_IC; /* Expression: InitialConditionForFilter * Referenced by: '<S7>/Filter' */ real_T FilterCoefficient_Gain; /* Expression: N * Referenced by: '<S7>/Filter Coefficient' */ real_T IntegralGain_Gain; /* Expression: I * Referenced by: '<S7>/Integral Gain' */ real_T Integrator_IC; /* Expression: InitialConditionForIntegrator * Referenced by: '<S7>/Integrator' */ real_T ProportionalGain_Gain; /* Expression: P * Referenced by: '<S7>/Proportional Gain' */ real_T Switch_Threshold; /* Expression: 0 * Referenced by: '<S3>/Switch' */ real_T DerivativeGain_Gain_m; /* Expression: D * Referenced by: '<S8>/Derivative Gain' */ real_T Filter_IC_f; /* Expression: InitialConditionForFilter * Referenced by: '<S8>/Filter' */ real_T FilterCoefficient_Gain_h; /* Expression: N * Referenced by: '<S8>/Filter Coefficient' */ real_T IntegralGain_Gain_m; /* Expression: I * Referenced by: '<S8>/Integral Gain' */ real_T Integrator_IC_m; /* Expression: InitialConditionForIntegrator * Referenced by: '<S8>/Integrator' */ real_T ProportionalGain_Gain_h; /* Expression: P * Referenced by: '<S8>/Proportional Gain' */ real_T Switch_Threshold_a; /* Expression: 0 * Referenced by: '<S4>/Switch' */ real_T DerivativeGain_Gain_j; /* Expression: D * Referenced by: '<S9>/Derivative Gain' */ real_T Filter_IC_a; /* Expression: InitialConditionForFilter * Referenced by: '<S9>/Filter' */ real_T FilterCoefficient_Gain_o; /* Expression: N * Referenced by: '<S9>/Filter Coefficient' */ real_T IntegralGain_Gain_i; /* Expression: I * Referenced by: '<S9>/Integral Gain' */ real_T Integrator_IC_n; /* Expression: InitialConditionForIntegrator * Referenced by: '<S9>/Integrator' */ real_T ProportionalGain_Gain_a; /* Expression: P * Referenced by: '<S9>/Proportional Gain' */ real_T Switch_Threshold_e; /* Expression: 0 * Referenced by: '<S5>/Switch' */ real_T DerivativeGain_Gain_k; /* Expression: D * Referenced by: '<S10>/Derivative Gain' */ real_T Filter_IC_d; /* Expression: InitialConditionForFilter * Referenced by: '<S10>/Filter' */ real_T FilterCoefficient_Gain_b; /* Expression: N * Referenced by: '<S10>/Filter Coefficient' */ real_T IntegralGain_Gain_k; /* Expression: I * Referenced by: '<S10>/Integral Gain' */ real_T Integrator_IC_l; /* Expression: InitialConditionForIntegrator * Referenced by: '<S10>/Integrator' */ real_T ProportionalGain_Gain_e; /* Expression: P * Referenced by: '<S10>/Proportional Gain' */ real_T Switch_Threshold_b; /* Expression: 0 * Referenced by: '<S6>/Switch' */ int32_T PacketInput_PacketID; /* Expression: PacketID * Referenced by: '<S1>/Packet Input' */ int32_T PacketOutput_PacketID; /* Expression: PacketID * Referenced by: '<S1>/Packet Output' */ int32_T BitwiseOperator_BitMask; /* Expression: BitMask * Referenced by: '<S3>/Bitwise Operator' */ int32_T BitwiseOperator_BitMask_f; /* Expression: BitMask * Referenced by: '<S4>/Bitwise Operator' */ int32_T BitwiseOperator_BitMask_k; /* Expression: BitMask * Referenced by: '<S5>/Bitwise Operator' */ int32_T BitwiseOperator_BitMask_a; /* Expression: BitMask * Referenced by: '<S6>/Bitwise Operator' */ }; /* Real-time Model Data Structure */ struct RT_MODEL_autopilot { const char_T *path; const char_T *modelName; struct SimStruct_tag * *childSfunctions; const char_T *errorStatus; SS_SimMode simMode; RTWExtModeInfo *extModeInfo; RTWSolverInfo solverInfo; RTWSolverInfo *solverInfoPtr; void *sfcnInfo; /* * ModelData: * The following substructure contains information regarding * the data used in the model. */ struct { void *blockIO; const void *constBlockIO; real_T *defaultParam; ZCSigState *prevZCSigState; real_T *contStates; real_T *derivs; real_T *zcSignalValues; void *inputs; void *outputs; boolean_T *contStateDisabled; boolean_T zCCacheNeedsReset; boolean_T derivCacheNeedsReset; boolean_T blkStateChange; real_T odeF[1][8]; ODE1_IntgData intgData; } ModelData; /* * Sizes: * The following substructure contains sizes information * for many of the model attributes such as inputs, outputs, * dwork, sample times, etc. */ struct { uint32_T checksums[4]; uint32_T options; int_T numContStates; int_T numU; int_T numY; int_T numSampTimes; int_T numBlocks; int_T numBlockIO; int_T numBlockPrms; int_T numDwork; int_T numSFcnPrms; int_T numSFcns; int_T numIports; int_T numOports; int_T numNonSampZCs; int_T sysDirFeedThru; int_T rtwGenSfcn; } Sizes; /* * SpecialInfo: * The following substructure contains special information * related to other components that are dependent on RTW. */ struct { const void *mappingInfo; void *xpcData; } SpecialInfo; /* * Timing: * The following substructure contains information regarding * the timing information for the model. */ struct { time_T stepSize; uint32_T clockTick0; uint32_T clockTickH0; time_T stepSize0; uint32_T clockTick1; uint32_T clockTickH1; time_T stepSize1; time_T tStart; time_T tFinal; time_T timeOfLastOutput; void *timingData; real_T *varNextHitTimesList; SimTimeStep simTimeStep; boolean_T stopRequestedFlag; time_T *sampleTimes; time_T *offsetTimes; int_T *sampleTimeTaskIDPtr; int_T *sampleHits; int_T *perTaskSampleHits; time_T *t; time_T sampleTimesArray[2]; time_T offsetTimesArray[2]; int_T sampleTimeTaskIDArray[2]; int_T sampleHitArray[2]; int_T perTaskSampleHitsArray[4]; time_T tArray[2]; } Timing; /* * Work: * The following substructure contains information regarding * the work vectors in the model. */ struct { void *dwork; } Work; }; /* Block parameters (auto storage) */ extern Parameters_autopilot autopilot_P; /* Block signals (auto storage) */ extern BlockIO_autopilot autopilot_B; /* Continuous states (auto storage) */ extern ContinuousStates_autopilot autopilot_X; /* Block states (auto storage) */ extern D_Work_autopilot autopilot_DWork; /* External data declarations for dependent source files */ /* Zero-crossing (trigger) state */ extern PrevZCSigStates_autopilot autopilot_PrevZCSigState; /* Model entry point functions */ extern void autopilot_initialize(boolean_T firstTime); extern void autopilot_output(int_T tid); extern void autopilot_update(int_T tid); extern void autopilot_terminate(void); /* Real-time Model object */ extern struct RT_MODEL_autopilot *autopilot_M; /*- * The generated code includes comments that allow you to trace directly * back to the appropriate location in the model. The basic format * is <system>/block_name, where system is the system number (uniquely * assigned by Simulink) and block_name is the name of the block. * * Use the MATLAB hilite_system command to trace the generated code back * to the model. For example, * * hilite_system('<S3>') - opens system 3 * hilite_system('<S3>/Kp') - opens and selects block Kp which resides in S3 * * Here is the system hierarchy for this model * * '<Root>' : autopilot * '<S1>' : autopilot/APOLLO * '<S2>' : autopilot/Subsystem * '<S3>' : autopilot/reg pitch * '<S4>' : autopilot/reg roll * '<S5>' : autopilot/reg wys * '<S6>' : autopilot/reg yaw * '<S7>' : autopilot/reg pitch/PID Controller * '<S8>' : autopilot/reg roll/PID Controller * '<S9>' : autopilot/reg wys/PID Controller * '<S10>' : autopilot/reg yaw/PID Controller */ #endif /* RTW_HEADER_autopilot_h_ */
dagothar/apollo
src/simulink.h
<gh_stars>0 #ifndef _SIM_H #define _SIM_H #include <windows.h> #include "PracticalSocket.h" #include "main.h" #include "lander.h" /*--------------------------------------------------------------- STALE ---------------------------------------------------------------*/ //parametry komunikacji const short unsigned recv_port = 12003; //na jakim porcie odbior const short unsigned send_port = 12001; //na jakim porcie nadawanie const double sim_timeout = 0.5; //po ilu sek. uznac Simulink za odlaczony const unsigned int sim_f_mask = 0x00; //jake flagi moze zapisac Simulink(nie dziala) const short sim_n_param = 8; //ilosc parametrow wysylanych z programu do Simulinka //bity flag wyjsciowych do Simulinka enum SimSwitch { SIM_RESET = 0x01, //flagi programu SIM_ALIVE = 0x02, SIM_PAUSE = 0x04, SIM_M_0 = 0x10, //przelaczniki monostabilne SIM_M_1 = 0x20, SIM_M_2 = 0x40, SIM_M_3 = 0x80, SIM_B_0 = 0x100, //przelaczniki bistabilne SIM_B_1 = 0x200, SIM_B_2 = 0x400, SIM_B_3 = 0x800 }; /*--------------------------------------------------------------- DEFINICJE TYPOW ---------------------------------------------------------------*/ //typ struktury dla danych wejsciowych typedef struct { unsigned int flags; double u_main; //sterowanie glownym silnikiem double u_pitch; //sterowanie pochyleniem double u_yaw; //sterowanie odchyleniem double u_roll; //sterowanie przechyleniem } InData; //typ struktury dla danych wyjsciowych typedef struct { unsigned int flags; double dps, rcs; //pozostale paliwo/max.paliwo double x, y, z, h; //polozenie double dx, dy, dz; //predkosc double pitch, yaw, roll; //orientacja double dpitch, dyaw, droll; //predkosc katowa double param[sim_n_param]; //parametry wysylane do Simulinka } OutData; /*--------------------------------------------------------------- ZMIENNE ---------------------------------------------------------------*/ extern std::string sim_host; //adres na ktorym dziala Simulink extern InData sim_in; //bufor wejsciowy extern OutData sim_out; //bufor wyjsciowy extern bool simulink_online; //czy Simulink online extern clock_t sim_clock; //czas ostatniej komunikacji /*--------------------------------------------------------------- FUNKCJE ---------------------------------------------------------------*/ DWORD WINAPI com_thread(LPVOID param); //glowny watek komunikacji z Simulinkiem void com_update(); //update danych wejsciowych i wyjsciowych #endif
dagothar/apollo
apollo/simulink/autopilot_rtwin/autopilot_private.h
/* * autopilot_private.h * * Real-Time Workshop code generation for Simulink model "autopilot.mdl". * * Model version : 1.184 * Real-Time Workshop version : 7.5 (R2010a) 25-Jan-2010 * C source code generated on : Tue Jul 19 19:43:27 2011 * * Target selection: rtwin.tlc * Note: GRT includes extra infrastructure and instrumentation for prototyping * Embedded hardware selection: Generic->32-bit x86 compatible * Code generation objectives: Unspecified * Validation result: Not run */ #ifndef RTW_HEADER_autopilot_private_h_ #define RTW_HEADER_autopilot_private_h_ #include "rtwtypes.h" #ifndef __RTWTYPES_H__ #error This file requires rtwtypes.h to be included #else #ifdef TMWTYPES_PREVIOUSLY_INCLUDED #error This file requires rtwtypes.h to be included before tmwtypes.h #else /* Check for inclusion of an incorrect version of rtwtypes.h */ #ifndef RTWTYPES_ID_C08S16I32L32N32F1 #error This code was generated with a different "rtwtypes.h" than the file included #endif /* RTWTYPES_ID_C08S16I32L32N32F1 */ #endif /* TMWTYPES_PREVIOUSLY_INCLUDED */ #endif /* __RTWTYPES_H__ */ /* * UNUSED_PARAMETER(x) * Used to specify that a function parameter (argument) is required but not * accessed by the function body. */ #ifndef UNUSED_PARAMETER # if defined(__LCC__) # define UNUSED_PARAMETER(x) /* do nothing */ # else /* * This is the semi-ANSI standard way of indicating that an * unused function parameter is required. */ # define UNUSED_PARAMETER(x) (void) (x) # endif #endif /* private model entry point functions */ extern void autopilot_derivatives(void); #endif /* RTW_HEADER_autopilot_private_h_ */
dagothar/apollo
src/main.h
#ifndef _MAIN_H #define _MAIN_H /*--------------------------------------------------------------- STALE GLOBALNE ---------------------------------------------------------------*/ const double exp_dt = 0.01; //zalozona czestosc odswiezania stanu //stale fizyczne extern double g; //stala grawitacji extern double b_atm; //tarcie atmosfery /*--------------------------------------------------------------- ZMIENNE GLOBALNE ---------------------------------------------------------------*/ //flagi globalne extern bool exit_flag; //koniec programu extern bool pause_flag; //pauza //glowne zmienne czasu extern double t; extern double t_fps; //licznik czasu do pomiaru fps extern volatile double dt; //rzeczywiste dt #endif
dagothar/apollo
apollo/simulink/autopilot_rtwin/rtGetNaN.h
/* * rtGetNaN.h * * Real-Time Workshop code generation for Simulink model "autopilot.mdl". * * Model version : 1.184 * Real-Time Workshop version : 7.5 (R2010a) 25-Jan-2010 * C source code generated on : Tue Jul 19 19:43:27 2011 * * Target selection: rtwin.tlc * Note: GRT includes extra infrastructure and instrumentation for prototyping * Embedded hardware selection: Generic->32-bit x86 compatible * Code generation objectives: Unspecified * Validation result: Not run */ #ifndef RTW_HEADER_rtGetNaN_h_ #define RTW_HEADER_rtGetNaN_h_ #include <stddef.h> #include "rtwtypes.h" #include "rt_nonfinite.h" extern real_T rtGetNaN(void); extern real32_T rtGetNaNF(void); #endif /* RTW_HEADER_rtGetNaN_h_ */
dagothar/apollo
src/map.h
#ifndef _MAP_H #define _MAP_H #include <GL/glut.h> #include "model.h" #include "vectors.h" #include "init.h" #include "msg.h" #include "main.h" /*--------------------------------------------------------------- KOLORY I STALE ---------------------------------------------------------------*/ //kolor powierzchni const GLfloat moon_ambdiff[4] = { 0.30, 0.30, 0.30, 1.0 }; const GLfloat moon_specular[4] = { 0.05, 0.05, 0.05, 1.0 }; const GLfloat moon_shin = 0.0; //parametry powierzchni const int n_nodes = 256; //ilosc wezlow mapy powierzchni (potega 2) const double node_size = 30.0; //dlugosc pojedynczej krawedzi //parametry generatora fraktalnego extern double map_kh; //maksymalna wysokosc poczatkowych odchylen extern double map_eh; //co ile zmniejszac odchylenie w kolejnym kroku /*--------------------------------------------------------------- STRUKTURA ---------------------------------------------------------------*/ class Map { public: //konstruktory Map(); //glowne funkcje void generate(); //generuje dane void load(const char *filename); //wczytaj z pliku void save(const char *filename); //zapisz do pliku void display(); //wyswietla mape double get_height(double x, double y); //znajdz wysokosc w punkcie (x, y) private: double hmap[n_nodes+1][n_nodes+1]; //mapa wysokosci GLuint display_list; //lista wyswietlania //funkcje pomocnicze double noise(double amp); //szum void square(int x, int y, int step, double amp); //generator fraktalny void diamond(int x, int y, int step, double amp); void prepare(); //przygotowuje liste wyswietlania }; /*--------------------------------------------------------------- ZMIENNE ---------------------------------------------------------------*/ //mapa extern Map moon; //nazwa pliku z mapa extern char *map_file; #endif
dagothar/apollo
apollo/simulink/autopilot_rtwin/autopilot_types.h
<reponame>dagothar/apollo<filename>apollo/simulink/autopilot_rtwin/autopilot_types.h /* * autopilot_types.h * * Real-Time Workshop code generation for Simulink model "autopilot.mdl". * * Model version : 1.184 * Real-Time Workshop version : 7.5 (R2010a) 25-Jan-2010 * C source code generated on : Tue Jul 19 19:43:27 2011 * * Target selection: rtwin.tlc * Note: GRT includes extra infrastructure and instrumentation for prototyping * Embedded hardware selection: Generic->32-bit x86 compatible * Code generation objectives: Unspecified * Validation result: Not run */ #ifndef RTW_HEADER_autopilot_types_h_ #define RTW_HEADER_autopilot_types_h_ #include "rtwtypes.h" /* Parameters (auto storage) */ typedef struct Parameters_autopilot_ Parameters_autopilot; /* Forward declaration for rtModel */ typedef struct RT_MODEL_autopilot RT_MODEL_autopilot; #endif /* RTW_HEADER_autopilot_types_h_ */
dagothar/apollo
src/model.h
<reponame>dagothar/apollo #ifndef _MODEL_H #define _MODEL_H #include <vector> #include <sstream> #include <string> #include <fstream> #include <iostream> #include <GL/glut.h> //#include "log.h" struct Material { std::string name; GLfloat ambient[4]; GLfloat diffuse[4]; GLfloat specular[4]; GLfloat shininess; }; struct Vertex; struct Vertex { GLfloat x[3]; Vertex(); Vertex(GLfloat _x, GLfloat _y, GLfloat _z); }; typedef struct { int normal; int vertex[3]; int material; } Face; class Model { public: Model(); void load(const char *filename); void display(); void _display(); private: std::string matfile; std::vector<Material> materials; std::vector<Vertex> vertex; std::vector<Vertex> normals; std::vector<Face> faces; GLuint display_list; void load_materials(); void make_list(); }; #endif
dagothar/apollo
src/log.h
#ifndef _LOG_H #define _LOG_H #include "main.h" #include "lander.h" /*--------------------------------------------------------------- ZMIENNE ---------------------------------------------------------------*/ //zapis danych do pliku extern bool logging; //czy logowac? const double log_dt = 0.1; //co ile logowac dane extern double last_log; //czas zapisania ostatniego loga extern std::ofstream log_file; //plik z danymi /*--------------------------------------------------------------- FUNKCJE ---------------------------------------------------------------*/ //funkcja logowania do pliku void log(); #endif
dagothar/apollo
apollo/simulink/autopilot_rtwin/autopilot_data.c
<filename>apollo/simulink/autopilot_rtwin/autopilot_data.c<gh_stars>0 /* * autopilot_data.c * * Real-Time Workshop code generation for Simulink model "autopilot.mdl". * * Model version : 1.184 * Real-Time Workshop version : 7.5 (R2010a) 25-Jan-2010 * C source code generated on : Tue Jul 19 19:43:27 2011 * * Target selection: rtwin.tlc * Note: GRT includes extra infrastructure and instrumentation for prototyping * Embedded hardware selection: Generic->32-bit x86 compatible * Code generation objectives: Unspecified * Validation result: Not run */ #include "autopilot.h" #include "autopilot_private.h" /* Block parameters (auto storage) */ Parameters_autopilot autopilot_P = { 0.25, /* Expression: D * Referenced by: '<S7>/Derivative Gain' */ 0.0, /* Expression: InitialConditionForFilter * Referenced by: '<S7>/Filter' */ 10.0, /* Expression: N * Referenced by: '<S7>/Filter Coefficient' */ 0.001, /* Expression: I * Referenced by: '<S7>/Integral Gain' */ 0.0, /* Expression: InitialConditionForIntegrator * Referenced by: '<S7>/Integrator' */ 0.075, /* Expression: P * Referenced by: '<S7>/Proportional Gain' */ 0.0, /* Expression: 0 * Referenced by: '<S3>/Switch' */ 0.25, /* Expression: D * Referenced by: '<S8>/Derivative Gain' */ 0.0, /* Expression: InitialConditionForFilter * Referenced by: '<S8>/Filter' */ 10.0, /* Expression: N * Referenced by: '<S8>/Filter Coefficient' */ 0.001, /* Expression: I * Referenced by: '<S8>/Integral Gain' */ 0.0, /* Expression: InitialConditionForIntegrator * Referenced by: '<S8>/Integrator' */ 0.075, /* Expression: P * Referenced by: '<S8>/Proportional Gain' */ 0.0, /* Expression: 0 * Referenced by: '<S4>/Switch' */ 0.6, /* Expression: D * Referenced by: '<S9>/Derivative Gain' */ 0.0, /* Expression: InitialConditionForFilter * Referenced by: '<S9>/Filter' */ 10.0, /* Expression: N * Referenced by: '<S9>/Filter Coefficient' */ 0.01, /* Expression: I * Referenced by: '<S9>/Integral Gain' */ 0.0, /* Expression: InitialConditionForIntegrator * Referenced by: '<S9>/Integrator' */ 0.125, /* Expression: P * Referenced by: '<S9>/Proportional Gain' */ 0.0, /* Expression: 0 * Referenced by: '<S5>/Switch' */ 0.25, /* Expression: D * Referenced by: '<S10>/Derivative Gain' */ 0.0, /* Expression: InitialConditionForFilter * Referenced by: '<S10>/Filter' */ 10.0, /* Expression: N * Referenced by: '<S10>/Filter Coefficient' */ 0.001, /* Expression: I * Referenced by: '<S10>/Integral Gain' */ 0.0, /* Expression: InitialConditionForIntegrator * Referenced by: '<S10>/Integrator' */ 0.075, /* Expression: P * Referenced by: '<S10>/Proportional Gain' */ 0.0, /* Expression: 0 * Referenced by: '<S6>/Switch' */ 1, /* Expression: PacketID * Referenced by: '<S1>/Packet Input' */ 1, /* Expression: PacketID * Referenced by: '<S1>/Packet Output' */ 512, /* Expression: BitMask * Referenced by: '<S3>/Bitwise Operator' */ 1024, /* Expression: BitMask * Referenced by: '<S4>/Bitwise Operator' */ 256, /* Expression: BitMask * Referenced by: '<S5>/Bitwise Operator' */ 2048 /* Expression: BitMask * Referenced by: '<S6>/Bitwise Operator' */ };
dagothar/apollo
apollo/simulink/r_rtwin/r_data.c
<gh_stars>0 /* * r_data.c * * Real-Time Workshop code generation for Simulink model "r.mdl". * * Model version : 1.180 * Real-Time Workshop version : 7.5 (R2010a) 25-Jan-2010 * C source code generated on : Sun Jul 17 16:28:22 2011 * * Target selection: rtwin.tlc * Note: GRT includes extra infrastructure and instrumentation for prototyping * Embedded hardware selection: Generic->32-bit x86 compatible * Code generation objectives: Unspecified * Validation result: Not run */ #include "r.h" #include "r_private.h" /* Block parameters (auto storage) */ Parameters_r r_P = { 0.07, /* Expression: D * Referenced by: '<S7>/Derivative Gain' */ 0.0, /* Expression: InitialConditionForFilter * Referenced by: '<S7>/Filter' */ 10.0, /* Expression: N * Referenced by: '<S7>/Filter Coefficient' */ 1.0E-006, /* Expression: I * Referenced by: '<S7>/Integral Gain' */ 0.0, /* Expression: InitialConditionForIntegrator * Referenced by: '<S7>/Integrator' */ 0.012, /* Expression: P * Referenced by: '<S7>/Proportional Gain' */ 0.0, /* Expression: 0 * Referenced by: '<S3>/Switch' */ 0.07, /* Expression: D * Referenced by: '<S8>/Derivative Gain' */ 0.0, /* Expression: InitialConditionForFilter * Referenced by: '<S8>/Filter' */ 10.0, /* Expression: N * Referenced by: '<S8>/Filter Coefficient' */ 1.0E-006, /* Expression: I * Referenced by: '<S8>/Integral Gain' */ 0.0, /* Expression: InitialConditionForIntegrator * Referenced by: '<S8>/Integrator' */ 0.012, /* Expression: P * Referenced by: '<S8>/Proportional Gain' */ 0.0, /* Expression: 0 * Referenced by: '<S4>/Switch' */ 0.5, /* Expression: D * Referenced by: '<S9>/Derivative Gain' */ 0.0, /* Expression: InitialConditionForFilter * Referenced by: '<S9>/Filter' */ 10.0, /* Expression: N * Referenced by: '<S9>/Filter Coefficient' */ 0.01, /* Expression: I * Referenced by: '<S9>/Integral Gain' */ 0.0, /* Expression: InitialConditionForIntegrator * Referenced by: '<S9>/Integrator' */ 0.15, /* Expression: P * Referenced by: '<S9>/Proportional Gain' */ 0.0, /* Expression: 0 * Referenced by: '<S5>/Switch' */ 0.07, /* Expression: D * Referenced by: '<S10>/Derivative Gain' */ 0.0, /* Expression: InitialConditionForFilter * Referenced by: '<S10>/Filter' */ 10.0, /* Expression: N * Referenced by: '<S10>/Filter Coefficient' */ 1.0E-006, /* Expression: I * Referenced by: '<S10>/Integral Gain' */ 0.0, /* Expression: InitialConditionForIntegrator * Referenced by: '<S10>/Integrator' */ 0.012, /* Expression: P * Referenced by: '<S10>/Proportional Gain' */ 0.0, /* Expression: 0 * Referenced by: '<S6>/Switch' */ 1, /* Expression: PacketID * Referenced by: '<S1>/Packet Input' */ 1, /* Expression: PacketID * Referenced by: '<S1>/Packet Output' */ 512, /* Expression: BitMask * Referenced by: '<S3>/Bitwise Operator' */ 1024, /* Expression: BitMask * Referenced by: '<S4>/Bitwise Operator' */ 256, /* Expression: BitMask * Referenced by: '<S5>/Bitwise Operator' */ 2048 /* Expression: BitMask * Referenced by: '<S6>/Bitwise Operator' */ };
dagothar/apollo
src/init.h
<filename>src/init.h<gh_stars>0 #ifndef _INIT_H #define _INIT_H #include "vectors.h" #include "display.h" #include "map.h" #include "main.h" /*--------------------------------------------------------------- KOLORY ---------------------------------------------------------------*/ //kolory const float thr_color[4] = { 0.5, 0.0, 0.0, 0.7 }; const float bar_color[4] = { 1.0, 1.0, 1.0, 0.3 }; const float dps_fuel_color[4] = { 0.0, 0.5, 0.0, 0.7 }; const float rcs_fuel_color[4] = { 0.5, 0.5, 0.0, 0.7 }; const float info_color[4] = { 0.1, 0.1, 0.1, 0.4 }; const float hud_color[4] = { 0.87,0.73,0.13,1.0 }; const float text_color[4] = { 1.0, 1.0, 1.0, 1.0 }; const float msg_color[4] = { 1.0, 0.0, 0.0, 1.0 }; const float f_shinn = 0.1; // kolory const float no_emiss[4] = { 0.0, 0.0, 0.0, 0.0 }; const float dps_color[4] = { 0.0, 0.0, 0.5, 0.0 }; const float aps_color[4] = { 0.5, 0.5, 0.5, 0.0 }; const float rcs_color[4] = { 0.5, 0.5, 0.5, 0.0 }; const float max_plume_alpha = 0.25; // swiatlo const GLfloat light_ambient[4] = { 0.2, 0.2, 0.2, 1.0 }; const GLfloat light_diffuse[4] = { 1.0, 1.0, 1.0, 1.0 }; const GLfloat light_specular[4] = { 1.0, 1.0, 1.0, 1.0 }; const GLfloat light_position[4] = { -5000.0, -5000.0, 4000.0, 1.0 }; //uchwyt glownego okna extern int window; /*--------------------------------------------------------------- ZMIENNE GLOBALNE ---------------------------------------------------------------*/ //aktualny stan klawiszy extern volatile bool keys[256]; /*--------------------------------------------------------------- FUNKCJE ---------------------------------------------------------------*/ //interpretuj parametry linii komend void cmd_line(); //zmiana rozmiaru okna void resize(int width, int height); //wczytywanie tekstur GLuint load_texture(const char *filename); //inicjalizuj GL void init_gl(int &argc, char *argv[]); #endif
dagothar/apollo
src/lander.h
#ifndef _LANDER_H #define _LANDER_H #include <vector> #include <GL/glut.h> #include "main.h" #include "init.h" #include "model.h" #include "vectors.h" #include "map.h" #include "simulink.h" #include "msg.h" /*--------------------------------------------------------------- STALE LADOWNIKA ---------------------------------------------------------------*/ //konfiguracja statku enum LCon { C_APS, //tylko czlon wstepujacy C_DPS, //tylko czlon zstepujacy C_STACK //oba czlony }; //masy [kg] const double l_d_mass_dry = 6244.0; //masa wlasna statku(APS+DPS) const double l_a_mass_dry = 2347.0; //masa wlasna statku (APS) const double l_dps_max = 8165.0; //masa paliwa glownego silnika DPS const double l_aps_max = 2353.0; //masa paliwa glownego silnika DPS const double l_rcs_max = 287.0; //masa paliwa silnikow rcs const double l_I_per_mass = 2.0; //moment bezwladnosci=masa*l_I_per_mass //predkosc przy jakiej ladownik ulega rozbiciu const double crash_speed = 10.0; //[m/s] //Model silnikow: G_e(s)=e_k/(e_T s + 1) //max. ciag silnikow [N] const double e_dps_k = 45040.0; //ciag silnika glownego czlonu ladujacego const double e_aps_k = 16000.0; //ciag silnika glownego czlonu wstepujacego const double e_rcs_k = 441.0; //ciag silnikow rcs const double e_dump_k = 1.0; //ciag przy zrzucie paliwa //stale czasowe silnikow [s] const double e_main_T = 0.5; //T silnika glownego const double e_rcs_T = 0.1; //T silnikow rcs const double e_dump_T = 1.0; //T przy zrzucie paliwa //zuzycie paliwa przy maksymalnym ciagu [kg/s] const double dps_flow_rate = 14.76; //silnik glowny DPS const double aps_flow_rate = 5.24; //silnik glowny APS const double rcs_flow_rate = 0.16; //silniki rcs const double dmp_flow_rate = 250.0; //zrzut paliwa //silniki //lista silnikow enum Engines { E_MAIN, E_U1, E_U2, E_U3, E_U4, E_D1, E_D2, E_D3, E_D4, E_F1, E_F2, E_B1, E_B2, E_L1, E_L2, E_R1, E_R2, E_DUMP }; enum EngineType { DPS, APS, RCS, DUMP }; //typ silnika //losowe zaburzenia pracy silnika extern bool turbulence; //czy wlaczone zaburzenia pracy silnika const double turb_thrust = 0.05; //procentowe odchylenia ciagu silnika const double turb_max_angle = 0.5; //maksymalne odchylenie wektora ciagu const double turb_change_chance = 15.0; //procent szans na zmiane wektora ciagu w danym kroku /*--------------------------------------------------------------- STRUKTURY ---------------------------------------------------------------*/ class Lander; //silniki class Engine { public: //konstruktory Engine(); Engine(Lander *_ship, EngineType _type, double x, double y, double z, double vx, double vy, double vz); //glowne funkcje void go(); //dzialanie void display(); //wyswietlenie wydechu //funkcje pomocnicze void reset(); //reset stanu void set_thrust(double _u); //ustawia wartosc zadana double get_thrust(); //zwraca osiagniety % max. ciagu double get_u(); //zwraca zadana wartosc private: Lander *ship; //do jakiego statku przynalezy silnik EngineType type; //typ silnika Vector position; //polozenie silnika Vector vthrust; //kierunek wektora ciagu //parametry silnika double k, T; //ciag, stala czasowa double u; //wartosc zadana double dx, x; //stan pracy silnika double x_T; //pomocniczy stan pracy x_T=x/T double y; //ciag wyjsciowy //zaklocenia Quaternion turb_rot; //kat obrotu wektora ciagu przy obliczaniu zaklocen double turb_dy; //zmiana ciagu silnika //zmienne pomocnicze double *fuel_source; //zrodlo paliwa double flow_rate; //pobor paliwa float f_color[4]; //kolor wydechu }; //ladownik class Lander { public: //konstruktor Lander(); //glowne funkcje void go(); //dzialanie void display(); //wyswietlenie //funkcje pomocnicze void setup(LCon conf); //wlasciwie inicjalizuje klase void reset(); //resetuje stan ladownika void kill(); //rozbij void order(double _u_main, Vector _u_rot, Vector _u_trans); //zadaje wejscie void set_position(double x, double y, double z); //ustawia nowe polozenie void set_orientation(double p, double y, double r); //ustawia nowa orientacje bool is_alive(); //zwraca stan ladownika void toggle_killrot(); //wlacza/wylacza killrot void toggle_dump(); //wlacza/wylacza zrzut paliwa double get_thrust(); //zwraca osiagniety % max ciagu glownego silnika double get_main_fuel(); //zwraca % pozostalego paliwa dps double get_rcs_fuel(); //zwraca % pozostalego paliwa rcs void draw_vectors(); //rysuje wektory void draw_vectors_fpp(); //jw. w trybi fpp void draw_info(); //wyswietla informacje o ladowniku void draw_hud(); //wyswietla hud w trybie fpp void draw_path(); //wyswietla sciezke void draw_shadow(); //wyswietla slad na ziemi void display_cam(); //wyswietla obraz z kamery private: //konfiguracja statku LCon configuration; //flagi bool alive; //czy zyje bool killrot; //czy wlaczony killrot bool fuel_dump; //zrzut paliwa? bool fuel_25, fuel_10; //flagi dla komunikatow bool rcs_25, rcs_10; //wartosci wejsciowe double u_main; //silnik glowny Vector u_rot; //sterowanie rotacja Vector u_trans; //sterowanie translacja //polozenie, predkosc, przyspieszenie Vector pos; Vector dpos; Vector d2pos; double h; //wysokosc nad powierzchnia //polozenie, predkosc, przyspieszenie katowe Quaternion fi; Quaternion dfi; Vector d2fi; //katy Eulera - pitch, yaw, roll - pochylenie, odchylenie, przechylenie Vector fi_euler; //orientacja Vector fi_euler_p; //poprzednia orientacja Vector dfi_euler; //predkosc obrotowa double mass, I; //masa, moment bezwladnosci double main_fuel; //pozostala ilosc paliwa silnika glownego double rcs_fuel; //pozostala ilosc paliwa RCS //wartosci poczatkowe double radius; double mass_dry; //masa bez palwa double main_fuel_max; //maksymalna ilosc paliwa glownego silnika double rcs_fuel_max; //maksymalna ilosc paliwa silnikow RCS Model *model; //model graficzny // silniki std::vector<Engine> engines; std::vector<Vector> path; //dane sciezki //funkcje void kill_rot(); //wbudowany autopilot killrot void sim_input(); //pobierz wartosci z Simulinka void steer(); //realizuje sterowania wlaczajac odpowiednie silniki //klasy i funkcje zaprzyjaznione friend class Engine; friend void display(); friend void log(); friend void com_update(); friend void go(); }; //ladownik extern Lander lander; #endif
dagothar/apollo
apollo/simulink/r_rtwin/r.c
/* * r.c * * Real-Time Workshop code generation for Simulink model "r.mdl". * * Model version : 1.180 * Real-Time Workshop version : 7.5 (R2010a) 25-Jan-2010 * C source code generated on : Sun Jul 17 16:28:22 2011 * * Target selection: rtwin.tlc * Note: GRT includes extra infrastructure and instrumentation for prototyping * Embedded hardware selection: Generic->32-bit x86 compatible * Code generation objectives: Unspecified * Validation result: Not run */ #include "r.h" #include "r_private.h" #include <stdio.h> #include "r_dt.h" /* options for Real-Time Windows Target board 0 */ static double RTWinBoardOptions0[] = { 2.130706433E+009, 12000.0, }; /* options for Real-Time Windows Target board 1 */ static double RTWinBoardOptions1[] = { 2.130706433E+009, 12003.0, }; /* list of Real-Time Windows Target boards */ const int RTWinBoardCount = 2; RTWINBOARD RTWinBoards[2] = { { "Standard_Devices/UDP_Protocol", 12001U, 2, RTWinBoardOptions0 }, { "Standard_Devices/UDP_Protocol", 12002U, 2, RTWinBoardOptions1 }, }; /* Block signals (auto storage) */ BlockIO_r r_B; /* Continuous states */ ContinuousStates_r r_X; /* Block states (auto storage) */ D_Work_r r_DWork; /* Previous zero-crossings (trigger) states */ PrevZCSigStates_r r_PrevZCSigState; /* Real-time model */ RT_MODEL_r r_M_; RT_MODEL_r *r_M = &r_M_; /* * This function updates continuous states using the ODE1 fixed-step * solver algorithm */ static void rt_ertODEUpdateContinuousStates(RTWSolverInfo *si ) { time_T tnew = rtsiGetSolverStopTime(si); time_T h = rtsiGetStepSize(si); real_T *x = rtsiGetContStates(si); ODE1_IntgData *id = (ODE1_IntgData *)rtsiGetSolverData(si); real_T *f0 = id->f[0]; int_T i; int_T nXc = 8; rtsiSetSimTimeStep(si,MINOR_TIME_STEP); rtsiSetdX(si, f0); r_derivatives(); rtsiSetT(si, tnew); for (i = 0; i < nXc; i++) { *x += h * f0[i]; x++; } rtsiSetSimTimeStep(si,MAJOR_TIME_STEP); } /* Model output function */ void r_output(int_T tid) { /* local block i/o variables */ real_T rtb_Integrator; real_T rtb_Integrator_n; real_T rtb_Integrator_o; real_T rtb_Integrator_g; real_T rtb_Filter; real_T rtb_Sum_p; int32_T i; if (rtmIsMajorTimeStep(r_M)) { /* set solver stop time */ if (!(r_M->Timing.clockTick0+1)) { rtsiSetSolverStopTime(&r_M->solverInfo, ((r_M->Timing.clockTickH0 + 1) * r_M->Timing.stepSize0 * 4294967296.0)); } else { rtsiSetSolverStopTime(&r_M->solverInfo, ((r_M->Timing.clockTick0 + 1) * r_M->Timing.stepSize0 + r_M->Timing.clockTickH0 * r_M->Timing.stepSize0 * 4294967296.0)); } } /* end MajorTimeStep */ /* Update absolute time of base rate at minor time step */ if (rtmIsMinorTimeStep(r_M)) { r_M->Timing.t[0] = rtsiGetT(&r_M->solverInfo); } if (rtmIsMajorTimeStep(r_M)) { /* S-Function Block: <S1>/Packet Input */ { uint8_T indata[192U]; int status = RTBIO_DriverIO(0, STREAMINPUT, IOREAD, 192U, &r_P.PacketInput_PacketID, (double*) indata, NULL); if (status & 0x1) { RTWin_ANYTYPEPTR indp; indp.p_uint8_T = indata; r_B.PacketInput_o1 = *indp.p_int32_T++; r_B.PacketInput_o2 = *indp.p_int32_T++; r_B.PacketInput_o3[0] = *indp.p_real_T++; r_B.PacketInput_o3[1] = *indp.p_real_T++; r_B.PacketInput_o4[0] = *indp.p_real_T++; r_B.PacketInput_o4[1] = *indp.p_real_T++; r_B.PacketInput_o4[2] = *indp.p_real_T++; r_B.PacketInput_o4[3] = *indp.p_real_T++; r_B.PacketInput_o4[4] = *indp.p_real_T++; r_B.PacketInput_o4[5] = *indp.p_real_T++; r_B.PacketInput_o4[6] = *indp.p_real_T++; r_B.PacketInput_o5[0] = *indp.p_real_T++; r_B.PacketInput_o5[1] = *indp.p_real_T++; r_B.PacketInput_o5[2] = *indp.p_real_T++; r_B.PacketInput_o5[3] = *indp.p_real_T++; r_B.PacketInput_o5[4] = *indp.p_real_T++; r_B.PacketInput_o5[5] = *indp.p_real_T++; r_B.PacketInput_o6[0] = *indp.p_real_T++; r_B.PacketInput_o6[1] = *indp.p_real_T++; r_B.PacketInput_o6[2] = *indp.p_real_T++; r_B.PacketInput_o6[3] = *indp.p_real_T++; r_B.PacketInput_o6[4] = *indp.p_real_T++; r_B.PacketInput_o6[5] = *indp.p_real_T++; r_B.PacketInput_o6[6] = *indp.p_real_T++; r_B.PacketInput_o6[7] = *indp.p_real_T++; } } /* RateTransition: '<S1>/Rate Transition2' */ if (rtmIsMajorTimeStep(r_M)) { r_B.RateTransition2 = r_B.PacketInput_o1; } /* RateTransition: '<S1>/Rate Transition3' */ if (rtmIsMajorTimeStep(r_M)) { r_B.RateTransition3[0] = r_B.PacketInput_o3[0]; r_B.RateTransition3[1] = r_B.PacketInput_o3[1]; } /* RateTransition: '<S1>/Rate Transition4' */ if (rtmIsMajorTimeStep(r_M)) { for (i = 0; i < 7; i++) { r_B.RateTransition4[i] = r_B.PacketInput_o4[i]; } } /* RateTransition: '<S1>/Rate Transition5' */ if (rtmIsMajorTimeStep(r_M)) { for (i = 0; i < 6; i++) { r_B.RateTransition5[i] = r_B.PacketInput_o5[i]; } } /* RateTransition: '<S1>/Rate Transition6' */ if (rtmIsMajorTimeStep(r_M)) { memcpy((void *)(&r_B.RateTransition6[0]), (void *)(&r_B.PacketInput_o6[0]), sizeof(real_T) << 3U); } /* DataTypeConversion: '<S3>/Data Type Conversion' incorporates: * S-Function (sfix_bitop): '<S3>/Bitwise Operator' */ r_B.DataTypeConversion = (real_T)(r_B.RateTransition2 & r_P.BitwiseOperator_BitMask); /* Logic: '<S3>/Logical Operator' */ r_B.LogicalOperator = !(r_B.DataTypeConversion != 0.0); /* Sum: '<S3>/Sum' */ rtb_Sum_p = r_B.RateTransition6[5] - r_B.RateTransition5[0]; /* Gain: '<S7>/Derivative Gain' */ r_B.DerivativeGain = r_P.DerivativeGain_Gain * rtb_Sum_p; } /* Integrator: '<S7>/Filter' */ if (rtmIsMajorTimeStep(r_M)) { ZCEventType zcEvent; zcEvent = ((ZCEventType) ((r_B.LogicalOperator != (r_PrevZCSigState.Filter_Reset_ZCE == POS_ZCSIG)) && (r_PrevZCSigState.Filter_Reset_ZCE != UNINITIALIZED_ZCSIG))); /* evaluate zero-crossings and the level of the reset signal */ r_PrevZCSigState.Filter_Reset_ZCE = (ZCSigState) r_B.LogicalOperator; if (zcEvent || r_B.LogicalOperator) { r_X.Filter_CSTATE = r_P.Filter_IC; } } rtb_Filter = r_X.Filter_CSTATE; /* Gain: '<S7>/Filter Coefficient' incorporates: * Sum: '<S7>/SumD' */ r_B.FilterCoefficient = (r_B.DerivativeGain - rtb_Filter) * r_P.FilterCoefficient_Gain; if (rtmIsMajorTimeStep(r_M)) { /* Gain: '<S7>/Integral Gain' */ r_B.IntegralGain = r_P.IntegralGain_Gain * rtb_Sum_p; } /* Integrator: '<S7>/Integrator' */ if (rtmIsMajorTimeStep(r_M)) { ZCEventType zcEvent; zcEvent = ((ZCEventType) ((r_B.LogicalOperator != (r_PrevZCSigState.Integrator_Reset_ZCE == POS_ZCSIG)) && (r_PrevZCSigState.Integrator_Reset_ZCE != UNINITIALIZED_ZCSIG))); /* evaluate zero-crossings and the level of the reset signal */ r_PrevZCSigState.Integrator_Reset_ZCE = (ZCSigState) r_B.LogicalOperator; if (zcEvent || r_B.LogicalOperator) { r_X.Integrator_CSTATE = r_P.Integrator_IC; } } rtb_Integrator = r_X.Integrator_CSTATE; if (rtmIsMajorTimeStep(r_M)) { /* Gain: '<S7>/Proportional Gain' */ r_B.ProportionalGain = r_P.ProportionalGain_Gain * rtb_Sum_p; } /* Switch: '<S3>/Switch' incorporates: * Sum: '<S7>/Sum' */ if (r_B.DataTypeConversion > r_P.Switch_Threshold) { r_B.Switch = (r_B.ProportionalGain + rtb_Integrator) + r_B.FilterCoefficient; } else { r_B.Switch = 0.0; } if (rtmIsMajorTimeStep(r_M)) { /* DataTypeConversion: '<S4>/Data Type Conversion' incorporates: * S-Function (sfix_bitop): '<S4>/Bitwise Operator' */ r_B.DataTypeConversion_f = (real_T)(r_B.RateTransition2 & r_P.BitwiseOperator_BitMask_m); /* Logic: '<S4>/Logical Operator' */ r_B.LogicalOperator_d = !(r_B.DataTypeConversion_f != 0.0); /* Sum: '<S4>/Sum' */ rtb_Sum_p = r_B.RateTransition6[6] - r_B.RateTransition5[2]; /* Gain: '<S8>/Derivative Gain' */ r_B.DerivativeGain_f = r_P.DerivativeGain_Gain_i * rtb_Sum_p; } /* Integrator: '<S8>/Filter' */ if (rtmIsMajorTimeStep(r_M)) { ZCEventType zcEvent; zcEvent = ((ZCEventType) ((r_B.LogicalOperator_d != (r_PrevZCSigState.Filter_Reset_ZCE_d == POS_ZCSIG)) && (r_PrevZCSigState.Filter_Reset_ZCE_d != UNINITIALIZED_ZCSIG))); /* evaluate zero-crossings and the level of the reset signal */ r_PrevZCSigState.Filter_Reset_ZCE_d = (ZCSigState) r_B.LogicalOperator_d; if (zcEvent || r_B.LogicalOperator_d) { r_X.Filter_CSTATE_k = r_P.Filter_IC_k; } } rtb_Filter = r_X.Filter_CSTATE_k; /* Gain: '<S8>/Filter Coefficient' incorporates: * Sum: '<S8>/SumD' */ r_B.FilterCoefficient_k = (r_B.DerivativeGain_f - rtb_Filter) * r_P.FilterCoefficient_Gain_c; if (rtmIsMajorTimeStep(r_M)) { /* Gain: '<S8>/Integral Gain' */ r_B.IntegralGain_j = r_P.IntegralGain_Gain_e * rtb_Sum_p; } /* Integrator: '<S8>/Integrator' */ if (rtmIsMajorTimeStep(r_M)) { ZCEventType zcEvent; zcEvent = ((ZCEventType) ((r_B.LogicalOperator_d != (r_PrevZCSigState.Integrator_Reset_ZCE_d == POS_ZCSIG)) && (r_PrevZCSigState.Integrator_Reset_ZCE_d != UNINITIALIZED_ZCSIG))); /* evaluate zero-crossings and the level of the reset signal */ r_PrevZCSigState.Integrator_Reset_ZCE_d = (ZCSigState) r_B.LogicalOperator_d; if (zcEvent || r_B.LogicalOperator_d) { r_X.Integrator_CSTATE_p = r_P.Integrator_IC_d; } } rtb_Integrator_n = r_X.Integrator_CSTATE_p; if (rtmIsMajorTimeStep(r_M)) { /* Gain: '<S8>/Proportional Gain' */ r_B.ProportionalGain_c = r_P.ProportionalGain_Gain_e * rtb_Sum_p; } /* Switch: '<S4>/Switch' incorporates: * Sum: '<S8>/Sum' */ if (r_B.DataTypeConversion_f > r_P.Switch_Threshold_n) { r_B.Switch_f = (r_B.ProportionalGain_c + rtb_Integrator_n) + r_B.FilterCoefficient_k; } else { r_B.Switch_f = 0.0; } if (rtmIsMajorTimeStep(r_M)) { /* Sum: '<S5>/Sum' */ r_B.Sum = r_B.RateTransition6[4] - r_B.RateTransition4[3]; /* DataTypeConversion: '<S5>/Data Type Conversion' incorporates: * S-Function (sfix_bitop): '<S5>/Bitwise Operator' */ r_B.DataTypeConversion_j = (real_T)(r_B.RateTransition2 & r_P.BitwiseOperator_BitMask_n); /* Logic: '<S5>/Logical Operator' */ r_B.LogicalOperator_g = !(r_B.DataTypeConversion_j != 0.0); /* Gain: '<S9>/Derivative Gain' */ r_B.DerivativeGain_j = r_P.DerivativeGain_Gain_j * r_B.Sum; } /* Integrator: '<S9>/Filter' */ if (rtmIsMajorTimeStep(r_M)) { ZCEventType zcEvent; zcEvent = ((ZCEventType) ((r_B.LogicalOperator_g != (r_PrevZCSigState.Filter_Reset_ZCE_b == POS_ZCSIG)) && (r_PrevZCSigState.Filter_Reset_ZCE_b != UNINITIALIZED_ZCSIG))); /* evaluate zero-crossings and the level of the reset signal */ r_PrevZCSigState.Filter_Reset_ZCE_b = (ZCSigState) r_B.LogicalOperator_g; if (zcEvent || r_B.LogicalOperator_g) { r_X.Filter_CSTATE_e = r_P.Filter_IC_a; } } rtb_Filter = r_X.Filter_CSTATE_e; /* Gain: '<S9>/Filter Coefficient' incorporates: * Sum: '<S9>/SumD' */ r_B.FilterCoefficient_j = (r_B.DerivativeGain_j - rtb_Filter) * r_P.FilterCoefficient_Gain_j; if (rtmIsMajorTimeStep(r_M)) { /* Gain: '<S9>/Integral Gain' */ r_B.IntegralGain_d = r_P.IntegralGain_Gain_c * r_B.Sum; } /* Integrator: '<S9>/Integrator' */ if (rtmIsMajorTimeStep(r_M)) { ZCEventType zcEvent; zcEvent = ((ZCEventType) ((r_B.LogicalOperator_g != (r_PrevZCSigState.Integrator_Reset_ZCE_b == POS_ZCSIG)) && (r_PrevZCSigState.Integrator_Reset_ZCE_b != UNINITIALIZED_ZCSIG))); /* evaluate zero-crossings and the level of the reset signal */ r_PrevZCSigState.Integrator_Reset_ZCE_b = (ZCSigState) r_B.LogicalOperator_g; if (zcEvent || r_B.LogicalOperator_g) { r_X.Integrator_CSTATE_l = r_P.Integrator_IC_h; } } rtb_Integrator_o = r_X.Integrator_CSTATE_l; if (rtmIsMajorTimeStep(r_M)) { /* Gain: '<S9>/Proportional Gain' */ r_B.ProportionalGain_l = r_P.ProportionalGain_Gain_f * r_B.Sum; } /* Switch: '<S5>/Switch' incorporates: * Sum: '<S9>/Sum' */ if (r_B.DataTypeConversion_j > r_P.Switch_Threshold_i) { r_B.Switch_n = (r_B.ProportionalGain_l + rtb_Integrator_o) + r_B.FilterCoefficient_j; } else { r_B.Switch_n = 0.0; } if (rtmIsMajorTimeStep(r_M)) { /* DataTypeConversion: '<S6>/Data Type Conversion' incorporates: * S-Function (sfix_bitop): '<S6>/Bitwise Operator' */ r_B.DataTypeConversion_c = (real_T)(r_B.RateTransition2 & r_P.BitwiseOperator_BitMask_l); /* Logic: '<S6>/Logical Operator' */ r_B.LogicalOperator_l = !(r_B.DataTypeConversion_c != 0.0); /* Sum: '<S6>/Sum' */ rtb_Sum_p = r_B.RateTransition6[7] - r_B.RateTransition5[1]; /* Gain: '<S10>/Derivative Gain' */ r_B.DerivativeGain_ff = r_P.DerivativeGain_Gain_o * rtb_Sum_p; } /* Integrator: '<S10>/Filter' */ if (rtmIsMajorTimeStep(r_M)) { ZCEventType zcEvent; zcEvent = ((ZCEventType) ((r_B.LogicalOperator_l != (r_PrevZCSigState.Filter_Reset_ZCE_j == POS_ZCSIG)) && (r_PrevZCSigState.Filter_Reset_ZCE_j != UNINITIALIZED_ZCSIG))); /* evaluate zero-crossings and the level of the reset signal */ r_PrevZCSigState.Filter_Reset_ZCE_j = (ZCSigState) r_B.LogicalOperator_l; if (zcEvent || r_B.LogicalOperator_l) { r_X.Filter_CSTATE_g = r_P.Filter_IC_j; } } rtb_Filter = r_X.Filter_CSTATE_g; /* Gain: '<S10>/Filter Coefficient' incorporates: * Sum: '<S10>/SumD' */ r_B.FilterCoefficient_h = (r_B.DerivativeGain_ff - rtb_Filter) * r_P.FilterCoefficient_Gain_e; if (rtmIsMajorTimeStep(r_M)) { /* Gain: '<S10>/Integral Gain' */ r_B.IntegralGain_o = r_P.IntegralGain_Gain_d * rtb_Sum_p; } /* Integrator: '<S10>/Integrator' */ if (rtmIsMajorTimeStep(r_M)) { ZCEventType zcEvent; zcEvent = ((ZCEventType) ((r_B.LogicalOperator_l != (r_PrevZCSigState.Integrator_Reset_ZCE_h == POS_ZCSIG)) && (r_PrevZCSigState.Integrator_Reset_ZCE_h != UNINITIALIZED_ZCSIG))); /* evaluate zero-crossings and the level of the reset signal */ r_PrevZCSigState.Integrator_Reset_ZCE_h = (ZCSigState) r_B.LogicalOperator_l; if (zcEvent || r_B.LogicalOperator_l) { r_X.Integrator_CSTATE_n = r_P.Integrator_IC_m; } } rtb_Integrator_g = r_X.Integrator_CSTATE_n; if (rtmIsMajorTimeStep(r_M)) { /* Gain: '<S10>/Proportional Gain' */ r_B.ProportionalGain_g = r_P.ProportionalGain_Gain_h * rtb_Sum_p; } /* Switch: '<S6>/Switch' incorporates: * Sum: '<S10>/Sum' */ if (r_B.DataTypeConversion_c > r_P.Switch_Threshold_e) { r_B.Switch_m = (r_B.ProportionalGain_g + rtb_Integrator_g) + r_B.FilterCoefficient_h; } else { r_B.Switch_m = 0.0; } /* tid is required for a uniform function interface. * Argument tid is not used in the function. */ UNUSED_PARAMETER(tid); } /* Model update function */ void r_update(int_T tid) { if (rtmIsMajorTimeStep(r_M)) { /* S-Function Block: <S1>/Packet Output */ { uint8_T outdata[40U]; RTWin_ANYTYPEPTR outdp; outdp.p_uint8_T = outdata; *outdp.p_int32_T++ = (int32_T) 0.0; *outdp.p_int32_T++ = (int32_T) 0.0; *outdp.p_real_T++ = (real_T) r_B.Switch_n; *outdp.p_real_T++ = (real_T) r_B.Switch; *outdp.p_real_T++ = (real_T) r_B.Switch_m; *outdp.p_real_T++ = (real_T) r_B.Switch_f; RTBIO_DriverIO(1, STREAMOUTPUT, IOWRITE, 40U, &r_P.PacketOutput_PacketID, (double*) outdata, NULL); } } if (rtmIsMajorTimeStep(r_M)) { rt_ertODEUpdateContinuousStates(&r_M->solverInfo); } /* Update absolute time for base rate */ /* The "clockTick0" counts the number of times the code of this task has * been executed. The absolute time is the multiplication of "clockTick0" * and "Timing.stepSize0". Size of "clockTick0" ensures timer will not * overflow during the application lifespan selected. * Timer of this task consists of two 32 bit unsigned integers. * The two integers represent the low bits Timing.clockTick0 and the high bits * Timing.clockTickH0. When the low bit overflows to 0, the high bits increment. */ if (!(++r_M->Timing.clockTick0)) { ++r_M->Timing.clockTickH0; } r_M->Timing.t[0] = rtsiGetSolverStopTime(&r_M->solverInfo); if (rtmIsMajorTimeStep(r_M)) { /* Update absolute timer for sample time: [0.02s, 0.0s] */ /* The "clockTick1" counts the number of times the code of this task has * been executed. The absolute time is the multiplication of "clockTick1" * and "Timing.stepSize1". Size of "clockTick1" ensures timer will not * overflow during the application lifespan selected. * Timer of this task consists of two 32 bit unsigned integers. * The two integers represent the low bits Timing.clockTick1 and the high bits * Timing.clockTickH1. When the low bit overflows to 0, the high bits increment. */ if (!(++r_M->Timing.clockTick1)) { ++r_M->Timing.clockTickH1; } r_M->Timing.t[1] = r_M->Timing.clockTick1 * r_M->Timing.stepSize1 + r_M->Timing.clockTickH1 * r_M->Timing.stepSize1 * 4294967296.0; } /* tid is required for a uniform function interface. * Argument tid is not used in the function. */ UNUSED_PARAMETER(tid); } /* Derivatives for root system: '<Root>' */ void r_derivatives(void) { /* Derivatives for Integrator: '<S7>/Filter' */ { if (!r_B.LogicalOperator) { ((StateDerivatives_r *) r_M->ModelData.derivs)->Filter_CSTATE = r_B.FilterCoefficient; } else { /* level reset is active*/ ((StateDerivatives_r *) r_M->ModelData.derivs)->Filter_CSTATE = 0.0; } } /* Derivatives for Integrator: '<S7>/Integrator' */ { if (!r_B.LogicalOperator) { ((StateDerivatives_r *) r_M->ModelData.derivs)->Integrator_CSTATE = r_B.IntegralGain; } else { /* level reset is active*/ ((StateDerivatives_r *) r_M->ModelData.derivs)->Integrator_CSTATE = 0.0; } } /* Derivatives for Integrator: '<S8>/Filter' */ { if (!r_B.LogicalOperator_d) { ((StateDerivatives_r *) r_M->ModelData.derivs)->Filter_CSTATE_k = r_B.FilterCoefficient_k; } else { /* level reset is active*/ ((StateDerivatives_r *) r_M->ModelData.derivs)->Filter_CSTATE_k = 0.0; } } /* Derivatives for Integrator: '<S8>/Integrator' */ { if (!r_B.LogicalOperator_d) { ((StateDerivatives_r *) r_M->ModelData.derivs)->Integrator_CSTATE_p = r_B.IntegralGain_j; } else { /* level reset is active*/ ((StateDerivatives_r *) r_M->ModelData.derivs)->Integrator_CSTATE_p = 0.0; } } /* Derivatives for Integrator: '<S9>/Filter' */ { if (!r_B.LogicalOperator_g) { ((StateDerivatives_r *) r_M->ModelData.derivs)->Filter_CSTATE_e = r_B.FilterCoefficient_j; } else { /* level reset is active*/ ((StateDerivatives_r *) r_M->ModelData.derivs)->Filter_CSTATE_e = 0.0; } } /* Derivatives for Integrator: '<S9>/Integrator' */ { if (!r_B.LogicalOperator_g) { ((StateDerivatives_r *) r_M->ModelData.derivs)->Integrator_CSTATE_l = r_B.IntegralGain_d; } else { /* level reset is active*/ ((StateDerivatives_r *) r_M->ModelData.derivs)->Integrator_CSTATE_l = 0.0; } } /* Derivatives for Integrator: '<S10>/Filter' */ { if (!r_B.LogicalOperator_l) { ((StateDerivatives_r *) r_M->ModelData.derivs)->Filter_CSTATE_g = r_B.FilterCoefficient_h; } else { /* level reset is active*/ ((StateDerivatives_r *) r_M->ModelData.derivs)->Filter_CSTATE_g = 0.0; } } /* Derivatives for Integrator: '<S10>/Integrator' */ { if (!r_B.LogicalOperator_l) { ((StateDerivatives_r *) r_M->ModelData.derivs)->Integrator_CSTATE_n = r_B.IntegralGain_o; } else { /* level reset is active*/ ((StateDerivatives_r *) r_M->ModelData.derivs)->Integrator_CSTATE_n = 0.0; } } } /* Model initialize function */ void r_initialize(boolean_T firstTime) { (void)firstTime; /* Registration code */ /* initialize non-finites */ rt_InitInfAndNaN(sizeof(real_T)); /* initialize real-time model */ (void) memset((void *)r_M, 0, sizeof(RT_MODEL_r)); { /* Setup solver object */ rtsiSetSimTimeStepPtr(&r_M->solverInfo, &r_M->Timing.simTimeStep); rtsiSetTPtr(&r_M->solverInfo, &rtmGetTPtr(r_M)); rtsiSetStepSizePtr(&r_M->solverInfo, &r_M->Timing.stepSize0); rtsiSetdXPtr(&r_M->solverInfo, &r_M->ModelData.derivs); rtsiSetContStatesPtr(&r_M->solverInfo, &r_M->ModelData.contStates); rtsiSetNumContStatesPtr(&r_M->solverInfo, &r_M->Sizes.numContStates); rtsiSetErrorStatusPtr(&r_M->solverInfo, (&rtmGetErrorStatus(r_M))); rtsiSetRTModelPtr(&r_M->solverInfo, r_M); } rtsiSetSimTimeStep(&r_M->solverInfo, MAJOR_TIME_STEP); r_M->ModelData.intgData.f[0] = r_M->ModelData.odeF[0]; r_M->ModelData.contStates = ((real_T *) &r_X); rtsiSetSolverData(&r_M->solverInfo, (void *)&r_M->ModelData.intgData); rtsiSetSolverName(&r_M->solverInfo,"ode1"); /* Initialize timing info */ { int_T *mdlTsMap = r_M->Timing.sampleTimeTaskIDArray; mdlTsMap[0] = 0; mdlTsMap[1] = 1; r_M->Timing.sampleTimeTaskIDPtr = (&mdlTsMap[0]); r_M->Timing.sampleTimes = (&r_M->Timing.sampleTimesArray[0]); r_M->Timing.offsetTimes = (&r_M->Timing.offsetTimesArray[0]); /* task periods */ r_M->Timing.sampleTimes[0] = (0.0); r_M->Timing.sampleTimes[1] = (0.02); /* task offsets */ r_M->Timing.offsetTimes[0] = (0.0); r_M->Timing.offsetTimes[1] = (0.0); } rtmSetTPtr(r_M, &r_M->Timing.tArray[0]); { int_T *mdlSampleHits = r_M->Timing.sampleHitArray; mdlSampleHits[0] = 1; mdlSampleHits[1] = 1; r_M->Timing.sampleHits = (&mdlSampleHits[0]); } rtmSetTFinal(r_M, -1); r_M->Timing.stepSize0 = 0.02; r_M->Timing.stepSize1 = 0.02; /* external mode info */ r_M->Sizes.checksums[0] = (2146525147U); r_M->Sizes.checksums[1] = (114594147U); r_M->Sizes.checksums[2] = (3439338169U); r_M->Sizes.checksums[3] = (2421275999U); { static const sysRanDType rtAlwaysEnabled = SUBSYS_RAN_BC_ENABLE; static RTWExtModeInfo rt_ExtModeInfo; static const sysRanDType *systemRan[5]; r_M->extModeInfo = (&rt_ExtModeInfo); rteiSetSubSystemActiveVectorAddresses(&rt_ExtModeInfo, systemRan); systemRan[0] = &rtAlwaysEnabled; systemRan[1] = &rtAlwaysEnabled; systemRan[2] = &rtAlwaysEnabled; systemRan[3] = &rtAlwaysEnabled; systemRan[4] = &rtAlwaysEnabled; rteiSetModelMappingInfoPtr(r_M->extModeInfo, &r_M->SpecialInfo.mappingInfo); rteiSetChecksumsPtr(r_M->extModeInfo, r_M->Sizes.checksums); rteiSetTPtr(r_M->extModeInfo, rtmGetTPtr(r_M)); } r_M->solverInfoPtr = (&r_M->solverInfo); r_M->Timing.stepSize = (0.02); rtsiSetFixedStepSize(&r_M->solverInfo, 0.02); rtsiSetSolverMode(&r_M->solverInfo, SOLVER_MODE_SINGLETASKING); /* block I/O */ r_M->ModelData.blockIO = ((void *) &r_B); (void) memset(((void *) &r_B), 0, sizeof(BlockIO_r)); /* parameters */ r_M->ModelData.defaultParam = ((real_T *)&r_P); /* states (continuous) */ { real_T *x = (real_T *) &r_X; r_M->ModelData.contStates = (x); (void) memset((void *)&r_X, 0, sizeof(ContinuousStates_r)); } /* states (dwork) */ r_M->Work.dwork = ((void *) &r_DWork); (void) memset((void *)&r_DWork, 0, sizeof(D_Work_r)); /* data type transition information */ { static DataTypeTransInfo dtInfo; (void) memset((char_T *) &dtInfo, 0, sizeof(dtInfo)); r_M->SpecialInfo.mappingInfo = (&dtInfo); dtInfo.numDataTypes = 14; dtInfo.dataTypeSizes = &rtDataTypeSizes[0]; dtInfo.dataTypeNames = &rtDataTypeNames[0]; /* Block I/O transition table */ dtInfo.B = &rtBTransTable; /* Parameters transition table */ dtInfo.P = &rtPTransTable; } r_PrevZCSigState.Filter_Reset_ZCE = UNINITIALIZED_ZCSIG; r_PrevZCSigState.Integrator_Reset_ZCE = UNINITIALIZED_ZCSIG; r_PrevZCSigState.Filter_Reset_ZCE_d = UNINITIALIZED_ZCSIG; r_PrevZCSigState.Integrator_Reset_ZCE_d = UNINITIALIZED_ZCSIG; r_PrevZCSigState.Filter_Reset_ZCE_b = UNINITIALIZED_ZCSIG; r_PrevZCSigState.Integrator_Reset_ZCE_b = UNINITIALIZED_ZCSIG; r_PrevZCSigState.Filter_Reset_ZCE_j = UNINITIALIZED_ZCSIG; r_PrevZCSigState.Integrator_Reset_ZCE_h = UNINITIALIZED_ZCSIG; } /* Model terminate function */ void r_terminate(void) { /* S-Function Block: <S1>/Packet Output */ /* no final value should be set */ } /*========================================================================* * Start of GRT compatible call interface * *========================================================================*/ /* Solver interface called by GRT_Main */ #ifndef USE_GENERATED_SOLVER void rt_ODECreateIntegrationData(RTWSolverInfo *si) { UNUSED_PARAMETER(si); return; } /* do nothing */ void rt_ODEDestroyIntegrationData(RTWSolverInfo *si) { UNUSED_PARAMETER(si); return; } /* do nothing */ void rt_ODEUpdateContinuousStates(RTWSolverInfo *si) { UNUSED_PARAMETER(si); return; } /* do nothing */ #endif void MdlOutputs(int_T tid) { r_output(tid); } void MdlUpdate(int_T tid) { r_update(tid); } void MdlInitializeSizes(void) { r_M->Sizes.numContStates = (8); /* Number of continuous states */ r_M->Sizes.numY = (0); /* Number of model outputs */ r_M->Sizes.numU = (0); /* Number of model inputs */ r_M->Sizes.sysDirFeedThru = (0); /* The model is not direct feedthrough */ r_M->Sizes.numSampTimes = (2); /* Number of sample times */ r_M->Sizes.numBlocks = (76); /* Number of blocks */ r_M->Sizes.numBlockIO = (40); /* Number of block outputs */ r_M->Sizes.numBlockPrms = (34); /* Sum of parameter "widths" */ } void MdlInitializeSampleTimes(void) { } void MdlInitialize(void) { /* InitializeConditions for Integrator: '<S7>/Filter' */ r_X.Filter_CSTATE = r_P.Filter_IC; /* InitializeConditions for Integrator: '<S7>/Integrator' */ r_X.Integrator_CSTATE = r_P.Integrator_IC; /* InitializeConditions for Integrator: '<S8>/Filter' */ r_X.Filter_CSTATE_k = r_P.Filter_IC_k; /* InitializeConditions for Integrator: '<S8>/Integrator' */ r_X.Integrator_CSTATE_p = r_P.Integrator_IC_d; /* InitializeConditions for Integrator: '<S9>/Filter' */ r_X.Filter_CSTATE_e = r_P.Filter_IC_a; /* InitializeConditions for Integrator: '<S9>/Integrator' */ r_X.Integrator_CSTATE_l = r_P.Integrator_IC_h; /* InitializeConditions for Integrator: '<S10>/Filter' */ r_X.Filter_CSTATE_g = r_P.Filter_IC_j; /* InitializeConditions for Integrator: '<S10>/Integrator' */ r_X.Integrator_CSTATE_n = r_P.Integrator_IC_m; } void MdlStart(void) { /* S-Function Block: <S1>/Packet Output */ /* no initial value should be set */ MdlInitialize(); } void MdlTerminate(void) { r_terminate(); } RT_MODEL_r *r(void) { r_initialize(1); return r_M; } /*========================================================================* * End of GRT compatible call interface * *========================================================================*/
dagothar/apollo
src/msg.h
<reponame>dagothar/apollo<filename>src/msg.h #ifndef _MSG_H #define _MSG_H #include <vector> #include <string> #include <GL/glut.h> #include "main.h" #include "init.h" /*--------------------------------------------------------------- STALE ---------------------------------------------------------------*/ //typy wiadomosci enum MsgType { MSG_OK, MSG_INFO, MSG_WARN, MSG_ALRM, _MSG_N }; //definicja typu wiadomosci typedef struct { std::string text; MsgType type; } Message; //maksymalna ilosc wiadomosci const int max_messages = 5; //kolory wiadomosci const GLfloat msg_colors[_MSG_N][4] = { {0.0, 1.0, 0.0, 1.0}, {1.0, 1.0, 1.0, 1.0}, {1.0, 1.0, 0.0, 1.0}, {1.0, 0.0, 0.0, 1.0} }; /*--------------------------------------------------------------- ZMIENNE ---------------------------------------------------------------*/ //wektor wiadomosci extern std::vector<Message> msg_list; /*--------------------------------------------------------------- FUNKCJE ---------------------------------------------------------------*/ //wyswietla kolejna wiadomosc void message(std::string msg, MsgType type); //czysci bufor wiadomosci void clear_messages(); //wyswietla wiadomosci void display_messages(); #endif
dagothar/apollo
apollo/simulink/autopilot_rtwin/autopilot.c
<reponame>dagothar/apollo<gh_stars>0 /* * autopilot.c * * Real-Time Workshop code generation for Simulink model "autopilot.mdl". * * Model version : 1.184 * Real-Time Workshop version : 7.5 (R2010a) 25-Jan-2010 * C source code generated on : Tue Jul 19 19:43:27 2011 * * Target selection: rtwin.tlc * Note: GRT includes extra infrastructure and instrumentation for prototyping * Embedded hardware selection: Generic->32-bit x86 compatible * Code generation objectives: Unspecified * Validation result: Not run */ #include "autopilot.h" #include "autopilot_private.h" #include <stdio.h> #include "autopilot_dt.h" /* options for Real-Time Windows Target board 0 */ static double RTWinBoardOptions0[] = { 2.130706433E+009, 12000.0, }; /* options for Real-Time Windows Target board 1 */ static double RTWinBoardOptions1[] = { 2.130706433E+009, 12003.0, }; /* list of Real-Time Windows Target boards */ const int RTWinBoardCount = 2; RTWINBOARD RTWinBoards[2] = { { "Standard_Devices/UDP_Protocol", 12001U, 2, RTWinBoardOptions0 }, { "Standard_Devices/UDP_Protocol", 12002U, 2, RTWinBoardOptions1 }, }; /* Block signals (auto storage) */ BlockIO_autopilot autopilot_B; /* Continuous states */ ContinuousStates_autopilot autopilot_X; /* Block states (auto storage) */ D_Work_autopilot autopilot_DWork; /* Previous zero-crossings (trigger) states */ PrevZCSigStates_autopilot autopilot_PrevZCSigState; /* Real-time model */ RT_MODEL_autopilot autopilot_M_; RT_MODEL_autopilot *autopilot_M = &autopilot_M_; /* * This function updates continuous states using the ODE1 fixed-step * solver algorithm */ static void rt_ertODEUpdateContinuousStates(RTWSolverInfo *si ) { time_T tnew = rtsiGetSolverStopTime(si); time_T h = rtsiGetStepSize(si); real_T *x = rtsiGetContStates(si); ODE1_IntgData *id = (ODE1_IntgData *)rtsiGetSolverData(si); real_T *f0 = id->f[0]; int_T i; int_T nXc = 8; rtsiSetSimTimeStep(si,MINOR_TIME_STEP); rtsiSetdX(si, f0); autopilot_derivatives(); rtsiSetT(si, tnew); for (i = 0; i < nXc; i++) { *x += h * f0[i]; x++; } rtsiSetSimTimeStep(si,MAJOR_TIME_STEP); } /* Model output function */ void autopilot_output(int_T tid) { /* local block i/o variables */ real_T rtb_Integrator; real_T rtb_Integrator_i; real_T rtb_Integrator_n; real_T rtb_Integrator_j; real_T rtb_Filter; real_T rtb_Sum_l; int32_T i; if (rtmIsMajorTimeStep(autopilot_M)) { /* set solver stop time */ if (!(autopilot_M->Timing.clockTick0+1)) { rtsiSetSolverStopTime(&autopilot_M->solverInfo, ((autopilot_M->Timing.clockTickH0 + 1) * autopilot_M->Timing.stepSize0 * 4294967296.0)); } else { rtsiSetSolverStopTime(&autopilot_M->solverInfo, ((autopilot_M->Timing.clockTick0 + 1) * autopilot_M->Timing.stepSize0 + autopilot_M->Timing.clockTickH0 * autopilot_M->Timing.stepSize0 * 4294967296.0)); } } /* end MajorTimeStep */ /* Update absolute time of base rate at minor time step */ if (rtmIsMinorTimeStep(autopilot_M)) { autopilot_M->Timing.t[0] = rtsiGetT(&autopilot_M->solverInfo); } if (rtmIsMajorTimeStep(autopilot_M)) { /* S-Function Block: <S1>/Packet Input */ { uint8_T indata[192U]; int status = RTBIO_DriverIO(0, STREAMINPUT, IOREAD, 192U, &autopilot_P.PacketInput_PacketID, (double*) indata, NULL); if (status & 0x1) { RTWin_ANYTYPEPTR indp; indp.p_uint8_T = indata; autopilot_B.PacketInput_o1 = *indp.p_int32_T++; autopilot_B.PacketInput_o2 = *indp.p_int32_T++; autopilot_B.PacketInput_o3[0] = *indp.p_real_T++; autopilot_B.PacketInput_o3[1] = *indp.p_real_T++; autopilot_B.PacketInput_o4[0] = *indp.p_real_T++; autopilot_B.PacketInput_o4[1] = *indp.p_real_T++; autopilot_B.PacketInput_o4[2] = *indp.p_real_T++; autopilot_B.PacketInput_o4[3] = *indp.p_real_T++; autopilot_B.PacketInput_o4[4] = *indp.p_real_T++; autopilot_B.PacketInput_o4[5] = *indp.p_real_T++; autopilot_B.PacketInput_o4[6] = *indp.p_real_T++; autopilot_B.PacketInput_o5[0] = *indp.p_real_T++; autopilot_B.PacketInput_o5[1] = *indp.p_real_T++; autopilot_B.PacketInput_o5[2] = *indp.p_real_T++; autopilot_B.PacketInput_o5[3] = *indp.p_real_T++; autopilot_B.PacketInput_o5[4] = *indp.p_real_T++; autopilot_B.PacketInput_o5[5] = *indp.p_real_T++; autopilot_B.PacketInput_o6[0] = *indp.p_real_T++; autopilot_B.PacketInput_o6[1] = *indp.p_real_T++; autopilot_B.PacketInput_o6[2] = *indp.p_real_T++; autopilot_B.PacketInput_o6[3] = *indp.p_real_T++; autopilot_B.PacketInput_o6[4] = *indp.p_real_T++; autopilot_B.PacketInput_o6[5] = *indp.p_real_T++; autopilot_B.PacketInput_o6[6] = *indp.p_real_T++; autopilot_B.PacketInput_o6[7] = *indp.p_real_T++; } } /* RateTransition: '<S1>/Rate Transition2' */ if (rtmIsMajorTimeStep(autopilot_M)) { autopilot_B.RateTransition2 = autopilot_B.PacketInput_o1; } /* RateTransition: '<S1>/Rate Transition3' */ if (rtmIsMajorTimeStep(autopilot_M)) { autopilot_B.RateTransition3[0] = autopilot_B.PacketInput_o3[0]; autopilot_B.RateTransition3[1] = autopilot_B.PacketInput_o3[1]; } /* RateTransition: '<S1>/Rate Transition4' */ if (rtmIsMajorTimeStep(autopilot_M)) { for (i = 0; i < 7; i++) { autopilot_B.RateTransition4[i] = autopilot_B.PacketInput_o4[i]; } } /* RateTransition: '<S1>/Rate Transition5' */ if (rtmIsMajorTimeStep(autopilot_M)) { for (i = 0; i < 6; i++) { autopilot_B.RateTransition5[i] = autopilot_B.PacketInput_o5[i]; } } /* RateTransition: '<S1>/Rate Transition6' */ if (rtmIsMajorTimeStep(autopilot_M)) { memcpy((void *)(&autopilot_B.RateTransition6[0]), (void *) (&autopilot_B.PacketInput_o6[0]), sizeof(real_T) << 3U); } /* DataTypeConversion: '<S3>/Data Type Conversion' incorporates: * S-Function (sfix_bitop): '<S3>/Bitwise Operator' */ autopilot_B.DataTypeConversion = (real_T)(autopilot_B.RateTransition2 & autopilot_P.BitwiseOperator_BitMask); /* Logic: '<S3>/Logical Operator' */ autopilot_B.LogicalOperator = !(autopilot_B.DataTypeConversion != 0.0); /* Sum: '<S3>/Sum' */ rtb_Sum_l = autopilot_B.RateTransition6[5] - autopilot_B.RateTransition5[0]; /* Gain: '<S7>/Derivative Gain' */ autopilot_B.DerivativeGain = autopilot_P.DerivativeGain_Gain * rtb_Sum_l; } /* Integrator: '<S7>/Filter' */ if (rtmIsMajorTimeStep(autopilot_M)) { ZCEventType zcEvent; zcEvent = ((ZCEventType) ((autopilot_B.LogicalOperator != (autopilot_PrevZCSigState.Filter_Reset_ZCE == POS_ZCSIG)) && (autopilot_PrevZCSigState.Filter_Reset_ZCE != UNINITIALIZED_ZCSIG))); /* evaluate zero-crossings and the level of the reset signal */ autopilot_PrevZCSigState.Filter_Reset_ZCE = (ZCSigState) autopilot_B.LogicalOperator; if (zcEvent || autopilot_B.LogicalOperator) { autopilot_X.Filter_CSTATE = autopilot_P.Filter_IC; } } rtb_Filter = autopilot_X.Filter_CSTATE; /* Gain: '<S7>/Filter Coefficient' incorporates: * Sum: '<S7>/SumD' */ autopilot_B.FilterCoefficient = (autopilot_B.DerivativeGain - rtb_Filter) * autopilot_P.FilterCoefficient_Gain; if (rtmIsMajorTimeStep(autopilot_M)) { /* Gain: '<S7>/Integral Gain' */ autopilot_B.IntegralGain = autopilot_P.IntegralGain_Gain * rtb_Sum_l; } /* Integrator: '<S7>/Integrator' */ if (rtmIsMajorTimeStep(autopilot_M)) { ZCEventType zcEvent; zcEvent = ((ZCEventType) ((autopilot_B.LogicalOperator != (autopilot_PrevZCSigState.Integrator_Reset_ZCE == POS_ZCSIG)) && (autopilot_PrevZCSigState.Integrator_Reset_ZCE != UNINITIALIZED_ZCSIG))); /* evaluate zero-crossings and the level of the reset signal */ autopilot_PrevZCSigState.Integrator_Reset_ZCE = (ZCSigState) autopilot_B.LogicalOperator; if (zcEvent || autopilot_B.LogicalOperator) { autopilot_X.Integrator_CSTATE = autopilot_P.Integrator_IC; } } rtb_Integrator = autopilot_X.Integrator_CSTATE; if (rtmIsMajorTimeStep(autopilot_M)) { /* Gain: '<S7>/Proportional Gain' */ autopilot_B.ProportionalGain = autopilot_P.ProportionalGain_Gain * rtb_Sum_l; } /* Switch: '<S3>/Switch' incorporates: * Sum: '<S7>/Sum' */ if (autopilot_B.DataTypeConversion > autopilot_P.Switch_Threshold) { autopilot_B.Switch = (autopilot_B.ProportionalGain + rtb_Integrator) + autopilot_B.FilterCoefficient; } else { autopilot_B.Switch = 0.0; } if (rtmIsMajorTimeStep(autopilot_M)) { /* DataTypeConversion: '<S4>/Data Type Conversion' incorporates: * S-Function (sfix_bitop): '<S4>/Bitwise Operator' */ autopilot_B.DataTypeConversion_o = (real_T)(autopilot_B.RateTransition2 & autopilot_P.BitwiseOperator_BitMask_f); /* Logic: '<S4>/Logical Operator' */ autopilot_B.LogicalOperator_n = !(autopilot_B.DataTypeConversion_o != 0.0); /* Sum: '<S4>/Sum' */ rtb_Sum_l = autopilot_B.RateTransition6[6] - autopilot_B.RateTransition5[2]; /* Gain: '<S8>/Derivative Gain' */ autopilot_B.DerivativeGain_e = autopilot_P.DerivativeGain_Gain_m * rtb_Sum_l; } /* Integrator: '<S8>/Filter' */ if (rtmIsMajorTimeStep(autopilot_M)) { ZCEventType zcEvent; zcEvent = ((ZCEventType) ((autopilot_B.LogicalOperator_n != (autopilot_PrevZCSigState.Filter_Reset_ZCE_k == POS_ZCSIG)) && (autopilot_PrevZCSigState.Filter_Reset_ZCE_k != UNINITIALIZED_ZCSIG))); /* evaluate zero-crossings and the level of the reset signal */ autopilot_PrevZCSigState.Filter_Reset_ZCE_k = (ZCSigState) autopilot_B.LogicalOperator_n; if (zcEvent || autopilot_B.LogicalOperator_n) { autopilot_X.Filter_CSTATE_l = autopilot_P.Filter_IC_f; } } rtb_Filter = autopilot_X.Filter_CSTATE_l; /* Gain: '<S8>/Filter Coefficient' incorporates: * Sum: '<S8>/SumD' */ autopilot_B.FilterCoefficient_f = (autopilot_B.DerivativeGain_e - rtb_Filter) * autopilot_P.FilterCoefficient_Gain_h; if (rtmIsMajorTimeStep(autopilot_M)) { /* Gain: '<S8>/Integral Gain' */ autopilot_B.IntegralGain_k = autopilot_P.IntegralGain_Gain_m * rtb_Sum_l; } /* Integrator: '<S8>/Integrator' */ if (rtmIsMajorTimeStep(autopilot_M)) { ZCEventType zcEvent; zcEvent = ((ZCEventType) ((autopilot_B.LogicalOperator_n != (autopilot_PrevZCSigState.Integrator_Reset_ZCE_k == POS_ZCSIG)) && (autopilot_PrevZCSigState.Integrator_Reset_ZCE_k != UNINITIALIZED_ZCSIG))); /* evaluate zero-crossings and the level of the reset signal */ autopilot_PrevZCSigState.Integrator_Reset_ZCE_k = (ZCSigState) autopilot_B.LogicalOperator_n; if (zcEvent || autopilot_B.LogicalOperator_n) { autopilot_X.Integrator_CSTATE_d = autopilot_P.Integrator_IC_m; } } rtb_Integrator_i = autopilot_X.Integrator_CSTATE_d; if (rtmIsMajorTimeStep(autopilot_M)) { /* Gain: '<S8>/Proportional Gain' */ autopilot_B.ProportionalGain_i = autopilot_P.ProportionalGain_Gain_h * rtb_Sum_l; } /* Switch: '<S4>/Switch' incorporates: * Sum: '<S8>/Sum' */ if (autopilot_B.DataTypeConversion_o > autopilot_P.Switch_Threshold_a) { autopilot_B.Switch_l = (autopilot_B.ProportionalGain_i + rtb_Integrator_i) + autopilot_B.FilterCoefficient_f; } else { autopilot_B.Switch_l = 0.0; } if (rtmIsMajorTimeStep(autopilot_M)) { /* Sum: '<S5>/Sum' */ autopilot_B.Sum = autopilot_B.RateTransition6[4] - autopilot_B.RateTransition4[3]; /* DataTypeConversion: '<S5>/Data Type Conversion' incorporates: * S-Function (sfix_bitop): '<S5>/Bitwise Operator' */ autopilot_B.DataTypeConversion_c = (real_T)(autopilot_B.RateTransition2 & autopilot_P.BitwiseOperator_BitMask_k); /* Logic: '<S5>/Logical Operator' */ autopilot_B.LogicalOperator_i = !(autopilot_B.DataTypeConversion_c != 0.0); /* Gain: '<S9>/Derivative Gain' */ autopilot_B.DerivativeGain_i = autopilot_P.DerivativeGain_Gain_j * autopilot_B.Sum; } /* Integrator: '<S9>/Filter' */ if (rtmIsMajorTimeStep(autopilot_M)) { ZCEventType zcEvent; zcEvent = ((ZCEventType) ((autopilot_B.LogicalOperator_i != (autopilot_PrevZCSigState.Filter_Reset_ZCE_a == POS_ZCSIG)) && (autopilot_PrevZCSigState.Filter_Reset_ZCE_a != UNINITIALIZED_ZCSIG))); /* evaluate zero-crossings and the level of the reset signal */ autopilot_PrevZCSigState.Filter_Reset_ZCE_a = (ZCSigState) autopilot_B.LogicalOperator_i; if (zcEvent || autopilot_B.LogicalOperator_i) { autopilot_X.Filter_CSTATE_i = autopilot_P.Filter_IC_a; } } rtb_Filter = autopilot_X.Filter_CSTATE_i; /* Gain: '<S9>/Filter Coefficient' incorporates: * Sum: '<S9>/SumD' */ autopilot_B.FilterCoefficient_c = (autopilot_B.DerivativeGain_i - rtb_Filter) * autopilot_P.FilterCoefficient_Gain_o; if (rtmIsMajorTimeStep(autopilot_M)) { /* Gain: '<S9>/Integral Gain' */ autopilot_B.IntegralGain_a = autopilot_P.IntegralGain_Gain_i * autopilot_B.Sum; } /* Integrator: '<S9>/Integrator' */ if (rtmIsMajorTimeStep(autopilot_M)) { ZCEventType zcEvent; zcEvent = ((ZCEventType) ((autopilot_B.LogicalOperator_i != (autopilot_PrevZCSigState.Integrator_Reset_ZCE_h == POS_ZCSIG)) && (autopilot_PrevZCSigState.Integrator_Reset_ZCE_h != UNINITIALIZED_ZCSIG))); /* evaluate zero-crossings and the level of the reset signal */ autopilot_PrevZCSigState.Integrator_Reset_ZCE_h = (ZCSigState) autopilot_B.LogicalOperator_i; if (zcEvent || autopilot_B.LogicalOperator_i) { autopilot_X.Integrator_CSTATE_e = autopilot_P.Integrator_IC_n; } } rtb_Integrator_n = autopilot_X.Integrator_CSTATE_e; if (rtmIsMajorTimeStep(autopilot_M)) { /* Gain: '<S9>/Proportional Gain' */ autopilot_B.ProportionalGain_o = autopilot_P.ProportionalGain_Gain_a * autopilot_B.Sum; } /* Switch: '<S5>/Switch' incorporates: * Sum: '<S9>/Sum' */ if (autopilot_B.DataTypeConversion_c > autopilot_P.Switch_Threshold_e) { autopilot_B.Switch_i = (autopilot_B.ProportionalGain_o + rtb_Integrator_n) + autopilot_B.FilterCoefficient_c; } else { autopilot_B.Switch_i = 0.0; } if (rtmIsMajorTimeStep(autopilot_M)) { /* DataTypeConversion: '<S6>/Data Type Conversion' incorporates: * S-Function (sfix_bitop): '<S6>/Bitwise Operator' */ autopilot_B.DataTypeConversion_l = (real_T)(autopilot_B.RateTransition2 & autopilot_P.BitwiseOperator_BitMask_a); /* Logic: '<S6>/Logical Operator' */ autopilot_B.LogicalOperator_d = !(autopilot_B.DataTypeConversion_l != 0.0); /* Sum: '<S6>/Sum' */ rtb_Sum_l = autopilot_B.RateTransition6[7] - autopilot_B.RateTransition5[1]; /* Gain: '<S10>/Derivative Gain' */ autopilot_B.DerivativeGain_ei = autopilot_P.DerivativeGain_Gain_k * rtb_Sum_l; } /* Integrator: '<S10>/Filter' */ if (rtmIsMajorTimeStep(autopilot_M)) { ZCEventType zcEvent; zcEvent = ((ZCEventType) ((autopilot_B.LogicalOperator_d != (autopilot_PrevZCSigState.Filter_Reset_ZCE_b == POS_ZCSIG)) && (autopilot_PrevZCSigState.Filter_Reset_ZCE_b != UNINITIALIZED_ZCSIG))); /* evaluate zero-crossings and the level of the reset signal */ autopilot_PrevZCSigState.Filter_Reset_ZCE_b = (ZCSigState) autopilot_B.LogicalOperator_d; if (zcEvent || autopilot_B.LogicalOperator_d) { autopilot_X.Filter_CSTATE_p = autopilot_P.Filter_IC_d; } } rtb_Filter = autopilot_X.Filter_CSTATE_p; /* Gain: '<S10>/Filter Coefficient' incorporates: * Sum: '<S10>/SumD' */ autopilot_B.FilterCoefficient_e = (autopilot_B.DerivativeGain_ei - rtb_Filter) * autopilot_P.FilterCoefficient_Gain_b; if (rtmIsMajorTimeStep(autopilot_M)) { /* Gain: '<S10>/Integral Gain' */ autopilot_B.IntegralGain_m = autopilot_P.IntegralGain_Gain_k * rtb_Sum_l; } /* Integrator: '<S10>/Integrator' */ if (rtmIsMajorTimeStep(autopilot_M)) { ZCEventType zcEvent; zcEvent = ((ZCEventType) ((autopilot_B.LogicalOperator_d != (autopilot_PrevZCSigState.Integrator_Reset_ZCE_j == POS_ZCSIG)) && (autopilot_PrevZCSigState.Integrator_Reset_ZCE_j != UNINITIALIZED_ZCSIG))); /* evaluate zero-crossings and the level of the reset signal */ autopilot_PrevZCSigState.Integrator_Reset_ZCE_j = (ZCSigState) autopilot_B.LogicalOperator_d; if (zcEvent || autopilot_B.LogicalOperator_d) { autopilot_X.Integrator_CSTATE_n = autopilot_P.Integrator_IC_l; } } rtb_Integrator_j = autopilot_X.Integrator_CSTATE_n; if (rtmIsMajorTimeStep(autopilot_M)) { /* Gain: '<S10>/Proportional Gain' */ autopilot_B.ProportionalGain_l = autopilot_P.ProportionalGain_Gain_e * rtb_Sum_l; } /* Switch: '<S6>/Switch' incorporates: * Sum: '<S10>/Sum' */ if (autopilot_B.DataTypeConversion_l > autopilot_P.Switch_Threshold_b) { autopilot_B.Switch_e = (autopilot_B.ProportionalGain_l + rtb_Integrator_j) + autopilot_B.FilterCoefficient_e; } else { autopilot_B.Switch_e = 0.0; } /* tid is required for a uniform function interface. * Argument tid is not used in the function. */ UNUSED_PARAMETER(tid); } /* Model update function */ void autopilot_update(int_T tid) { if (rtmIsMajorTimeStep(autopilot_M)) { /* S-Function Block: <S1>/Packet Output */ { uint8_T outdata[40U]; RTWin_ANYTYPEPTR outdp; outdp.p_uint8_T = outdata; *outdp.p_int32_T++ = (int32_T) 0.0; *outdp.p_int32_T++ = (int32_T) 0.0; *outdp.p_real_T++ = (real_T) autopilot_B.Switch_i; *outdp.p_real_T++ = (real_T) autopilot_B.Switch; *outdp.p_real_T++ = (real_T) autopilot_B.Switch_e; *outdp.p_real_T++ = (real_T) autopilot_B.Switch_l; RTBIO_DriverIO(1, STREAMOUTPUT, IOWRITE, 40U, &autopilot_P.PacketOutput_PacketID, (double*) outdata, NULL); } } if (rtmIsMajorTimeStep(autopilot_M)) { rt_ertODEUpdateContinuousStates(&autopilot_M->solverInfo); } /* Update absolute time for base rate */ /* The "clockTick0" counts the number of times the code of this task has * been executed. The absolute time is the multiplication of "clockTick0" * and "Timing.stepSize0". Size of "clockTick0" ensures timer will not * overflow during the application lifespan selected. * Timer of this task consists of two 32 bit unsigned integers. * The two integers represent the low bits Timing.clockTick0 and the high bits * Timing.clockTickH0. When the low bit overflows to 0, the high bits increment. */ if (!(++autopilot_M->Timing.clockTick0)) { ++autopilot_M->Timing.clockTickH0; } autopilot_M->Timing.t[0] = rtsiGetSolverStopTime(&autopilot_M->solverInfo); if (rtmIsMajorTimeStep(autopilot_M)) { /* Update absolute timer for sample time: [0.02s, 0.0s] */ /* The "clockTick1" counts the number of times the code of this task has * been executed. The absolute time is the multiplication of "clockTick1" * and "Timing.stepSize1". Size of "clockTick1" ensures timer will not * overflow during the application lifespan selected. * Timer of this task consists of two 32 bit unsigned integers. * The two integers represent the low bits Timing.clockTick1 and the high bits * Timing.clockTickH1. When the low bit overflows to 0, the high bits increment. */ if (!(++autopilot_M->Timing.clockTick1)) { ++autopilot_M->Timing.clockTickH1; } autopilot_M->Timing.t[1] = autopilot_M->Timing.clockTick1 * autopilot_M->Timing.stepSize1 + autopilot_M->Timing.clockTickH1 * autopilot_M->Timing.stepSize1 * 4294967296.0; } /* tid is required for a uniform function interface. * Argument tid is not used in the function. */ UNUSED_PARAMETER(tid); } /* Derivatives for root system: '<Root>' */ void autopilot_derivatives(void) { /* Derivatives for Integrator: '<S7>/Filter' */ { if (!autopilot_B.LogicalOperator) { ((StateDerivatives_autopilot *) autopilot_M->ModelData.derivs) ->Filter_CSTATE = autopilot_B.FilterCoefficient; } else { /* level reset is active*/ ((StateDerivatives_autopilot *) autopilot_M->ModelData.derivs) ->Filter_CSTATE = 0.0; } } /* Derivatives for Integrator: '<S7>/Integrator' */ { if (!autopilot_B.LogicalOperator) { ((StateDerivatives_autopilot *) autopilot_M->ModelData.derivs) ->Integrator_CSTATE = autopilot_B.IntegralGain; } else { /* level reset is active*/ ((StateDerivatives_autopilot *) autopilot_M->ModelData.derivs) ->Integrator_CSTATE = 0.0; } } /* Derivatives for Integrator: '<S8>/Filter' */ { if (!autopilot_B.LogicalOperator_n) { ((StateDerivatives_autopilot *) autopilot_M->ModelData.derivs) ->Filter_CSTATE_l = autopilot_B.FilterCoefficient_f; } else { /* level reset is active*/ ((StateDerivatives_autopilot *) autopilot_M->ModelData.derivs) ->Filter_CSTATE_l = 0.0; } } /* Derivatives for Integrator: '<S8>/Integrator' */ { if (!autopilot_B.LogicalOperator_n) { ((StateDerivatives_autopilot *) autopilot_M->ModelData.derivs) ->Integrator_CSTATE_d = autopilot_B.IntegralGain_k; } else { /* level reset is active*/ ((StateDerivatives_autopilot *) autopilot_M->ModelData.derivs) ->Integrator_CSTATE_d = 0.0; } } /* Derivatives for Integrator: '<S9>/Filter' */ { if (!autopilot_B.LogicalOperator_i) { ((StateDerivatives_autopilot *) autopilot_M->ModelData.derivs) ->Filter_CSTATE_i = autopilot_B.FilterCoefficient_c; } else { /* level reset is active*/ ((StateDerivatives_autopilot *) autopilot_M->ModelData.derivs) ->Filter_CSTATE_i = 0.0; } } /* Derivatives for Integrator: '<S9>/Integrator' */ { if (!autopilot_B.LogicalOperator_i) { ((StateDerivatives_autopilot *) autopilot_M->ModelData.derivs) ->Integrator_CSTATE_e = autopilot_B.IntegralGain_a; } else { /* level reset is active*/ ((StateDerivatives_autopilot *) autopilot_M->ModelData.derivs) ->Integrator_CSTATE_e = 0.0; } } /* Derivatives for Integrator: '<S10>/Filter' */ { if (!autopilot_B.LogicalOperator_d) { ((StateDerivatives_autopilot *) autopilot_M->ModelData.derivs) ->Filter_CSTATE_p = autopilot_B.FilterCoefficient_e; } else { /* level reset is active*/ ((StateDerivatives_autopilot *) autopilot_M->ModelData.derivs) ->Filter_CSTATE_p = 0.0; } } /* Derivatives for Integrator: '<S10>/Integrator' */ { if (!autopilot_B.LogicalOperator_d) { ((StateDerivatives_autopilot *) autopilot_M->ModelData.derivs) ->Integrator_CSTATE_n = autopilot_B.IntegralGain_m; } else { /* level reset is active*/ ((StateDerivatives_autopilot *) autopilot_M->ModelData.derivs) ->Integrator_CSTATE_n = 0.0; } } } /* Model initialize function */ void autopilot_initialize(boolean_T firstTime) { (void)firstTime; /* Registration code */ /* initialize non-finites */ rt_InitInfAndNaN(sizeof(real_T)); /* initialize real-time model */ (void) memset((void *)autopilot_M, 0, sizeof(RT_MODEL_autopilot)); { /* Setup solver object */ rtsiSetSimTimeStepPtr(&autopilot_M->solverInfo, &autopilot_M->Timing.simTimeStep); rtsiSetTPtr(&autopilot_M->solverInfo, &rtmGetTPtr(autopilot_M)); rtsiSetStepSizePtr(&autopilot_M->solverInfo, &autopilot_M->Timing.stepSize0); rtsiSetdXPtr(&autopilot_M->solverInfo, &autopilot_M->ModelData.derivs); rtsiSetContStatesPtr(&autopilot_M->solverInfo, &autopilot_M->ModelData.contStates); rtsiSetNumContStatesPtr(&autopilot_M->solverInfo, &autopilot_M->Sizes.numContStates); rtsiSetErrorStatusPtr(&autopilot_M->solverInfo, (&rtmGetErrorStatus (autopilot_M))); rtsiSetRTModelPtr(&autopilot_M->solverInfo, autopilot_M); } rtsiSetSimTimeStep(&autopilot_M->solverInfo, MAJOR_TIME_STEP); autopilot_M->ModelData.intgData.f[0] = autopilot_M->ModelData.odeF[0]; autopilot_M->ModelData.contStates = ((real_T *) &autopilot_X); rtsiSetSolverData(&autopilot_M->solverInfo, (void *) &autopilot_M->ModelData.intgData); rtsiSetSolverName(&autopilot_M->solverInfo,"ode1"); /* Initialize timing info */ { int_T *mdlTsMap = autopilot_M->Timing.sampleTimeTaskIDArray; mdlTsMap[0] = 0; mdlTsMap[1] = 1; autopilot_M->Timing.sampleTimeTaskIDPtr = (&mdlTsMap[0]); autopilot_M->Timing.sampleTimes = (&autopilot_M->Timing.sampleTimesArray[0]); autopilot_M->Timing.offsetTimes = (&autopilot_M->Timing.offsetTimesArray[0]); /* task periods */ autopilot_M->Timing.sampleTimes[0] = (0.0); autopilot_M->Timing.sampleTimes[1] = (0.02); /* task offsets */ autopilot_M->Timing.offsetTimes[0] = (0.0); autopilot_M->Timing.offsetTimes[1] = (0.0); } rtmSetTPtr(autopilot_M, &autopilot_M->Timing.tArray[0]); { int_T *mdlSampleHits = autopilot_M->Timing.sampleHitArray; mdlSampleHits[0] = 1; mdlSampleHits[1] = 1; autopilot_M->Timing.sampleHits = (&mdlSampleHits[0]); } rtmSetTFinal(autopilot_M, -1); autopilot_M->Timing.stepSize0 = 0.02; autopilot_M->Timing.stepSize1 = 0.02; /* external mode info */ autopilot_M->Sizes.checksums[0] = (3104530854U); autopilot_M->Sizes.checksums[1] = (3537910531U); autopilot_M->Sizes.checksums[2] = (3301480833U); autopilot_M->Sizes.checksums[3] = (2426685723U); { static const sysRanDType rtAlwaysEnabled = SUBSYS_RAN_BC_ENABLE; static RTWExtModeInfo rt_ExtModeInfo; static const sysRanDType *systemRan[5]; autopilot_M->extModeInfo = (&rt_ExtModeInfo); rteiSetSubSystemActiveVectorAddresses(&rt_ExtModeInfo, systemRan); systemRan[0] = &rtAlwaysEnabled; systemRan[1] = &rtAlwaysEnabled; systemRan[2] = &rtAlwaysEnabled; systemRan[3] = &rtAlwaysEnabled; systemRan[4] = &rtAlwaysEnabled; rteiSetModelMappingInfoPtr(autopilot_M->extModeInfo, &autopilot_M->SpecialInfo.mappingInfo); rteiSetChecksumsPtr(autopilot_M->extModeInfo, autopilot_M->Sizes.checksums); rteiSetTPtr(autopilot_M->extModeInfo, rtmGetTPtr(autopilot_M)); } autopilot_M->solverInfoPtr = (&autopilot_M->solverInfo); autopilot_M->Timing.stepSize = (0.02); rtsiSetFixedStepSize(&autopilot_M->solverInfo, 0.02); rtsiSetSolverMode(&autopilot_M->solverInfo, SOLVER_MODE_SINGLETASKING); /* block I/O */ autopilot_M->ModelData.blockIO = ((void *) &autopilot_B); (void) memset(((void *) &autopilot_B), 0, sizeof(BlockIO_autopilot)); /* parameters */ autopilot_M->ModelData.defaultParam = ((real_T *)&autopilot_P); /* states (continuous) */ { real_T *x = (real_T *) &autopilot_X; autopilot_M->ModelData.contStates = (x); (void) memset((void *)&autopilot_X, 0, sizeof(ContinuousStates_autopilot)); } /* states (dwork) */ autopilot_M->Work.dwork = ((void *) &autopilot_DWork); (void) memset((void *)&autopilot_DWork, 0, sizeof(D_Work_autopilot)); /* data type transition information */ { static DataTypeTransInfo dtInfo; (void) memset((char_T *) &dtInfo, 0, sizeof(dtInfo)); autopilot_M->SpecialInfo.mappingInfo = (&dtInfo); dtInfo.numDataTypes = 14; dtInfo.dataTypeSizes = &rtDataTypeSizes[0]; dtInfo.dataTypeNames = &rtDataTypeNames[0]; /* Block I/O transition table */ dtInfo.B = &rtBTransTable; /* Parameters transition table */ dtInfo.P = &rtPTransTable; } autopilot_PrevZCSigState.Filter_Reset_ZCE = UNINITIALIZED_ZCSIG; autopilot_PrevZCSigState.Integrator_Reset_ZCE = UNINITIALIZED_ZCSIG; autopilot_PrevZCSigState.Filter_Reset_ZCE_k = UNINITIALIZED_ZCSIG; autopilot_PrevZCSigState.Integrator_Reset_ZCE_k = UNINITIALIZED_ZCSIG; autopilot_PrevZCSigState.Filter_Reset_ZCE_a = UNINITIALIZED_ZCSIG; autopilot_PrevZCSigState.Integrator_Reset_ZCE_h = UNINITIALIZED_ZCSIG; autopilot_PrevZCSigState.Filter_Reset_ZCE_b = UNINITIALIZED_ZCSIG; autopilot_PrevZCSigState.Integrator_Reset_ZCE_j = UNINITIALIZED_ZCSIG; } /* Model terminate function */ void autopilot_terminate(void) { /* S-Function Block: <S1>/Packet Output */ /* no final value should be set */ } /*========================================================================* * Start of GRT compatible call interface * *========================================================================*/ /* Solver interface called by GRT_Main */ #ifndef USE_GENERATED_SOLVER void rt_ODECreateIntegrationData(RTWSolverInfo *si) { UNUSED_PARAMETER(si); return; } /* do nothing */ void rt_ODEDestroyIntegrationData(RTWSolverInfo *si) { UNUSED_PARAMETER(si); return; } /* do nothing */ void rt_ODEUpdateContinuousStates(RTWSolverInfo *si) { UNUSED_PARAMETER(si); return; } /* do nothing */ #endif void MdlOutputs(int_T tid) { autopilot_output(tid); } void MdlUpdate(int_T tid) { autopilot_update(tid); } void MdlInitializeSizes(void) { autopilot_M->Sizes.numContStates = (8);/* Number of continuous states */ autopilot_M->Sizes.numY = (0); /* Number of model outputs */ autopilot_M->Sizes.numU = (0); /* Number of model inputs */ autopilot_M->Sizes.sysDirFeedThru = (0);/* The model is not direct feedthrough */ autopilot_M->Sizes.numSampTimes = (2);/* Number of sample times */ autopilot_M->Sizes.numBlocks = (76); /* Number of blocks */ autopilot_M->Sizes.numBlockIO = (40);/* Number of block outputs */ autopilot_M->Sizes.numBlockPrms = (34);/* Sum of parameter "widths" */ } void MdlInitializeSampleTimes(void) { } void MdlInitialize(void) { /* InitializeConditions for Integrator: '<S7>/Filter' */ autopilot_X.Filter_CSTATE = autopilot_P.Filter_IC; /* InitializeConditions for Integrator: '<S7>/Integrator' */ autopilot_X.Integrator_CSTATE = autopilot_P.Integrator_IC; /* InitializeConditions for Integrator: '<S8>/Filter' */ autopilot_X.Filter_CSTATE_l = autopilot_P.Filter_IC_f; /* InitializeConditions for Integrator: '<S8>/Integrator' */ autopilot_X.Integrator_CSTATE_d = autopilot_P.Integrator_IC_m; /* InitializeConditions for Integrator: '<S9>/Filter' */ autopilot_X.Filter_CSTATE_i = autopilot_P.Filter_IC_a; /* InitializeConditions for Integrator: '<S9>/Integrator' */ autopilot_X.Integrator_CSTATE_e = autopilot_P.Integrator_IC_n; /* InitializeConditions for Integrator: '<S10>/Filter' */ autopilot_X.Filter_CSTATE_p = autopilot_P.Filter_IC_d; /* InitializeConditions for Integrator: '<S10>/Integrator' */ autopilot_X.Integrator_CSTATE_n = autopilot_P.Integrator_IC_l; } void MdlStart(void) { /* S-Function Block: <S1>/Packet Output */ /* no initial value should be set */ MdlInitialize(); } void MdlTerminate(void) { autopilot_terminate(); } RT_MODEL_autopilot *autopilot(void) { autopilot_initialize(1); return autopilot_M; } /*========================================================================* * End of GRT compatible call interface * *========================================================================*/
dagothar/apollo
src/sound.h
#ifndef _SOUND_H #define _SOUND_H #include <windows.h> #include <SDL/SDL.h> #include <SDL/SDL_mixer.h> #include "display.h" #include "main.h" /*--------------------------------------------------------------- LISTA DZWIEKOW ---------------------------------------------------------------*/ //maksymalna glosnosc silnikow const int snd_DSP_max = 32; const int snd_RCS_max = 16; enum { SND_NULL, //offset SND_DPS, SND_RCS, SND_CRASH, SND_N //tylko dla wyznaczenia dlugosci }; //dzwiek wlaczony? extern bool no_sound; //lista dzwiekow extern Mix_Chunk *sounds[SND_N]; //poziom glosnosci silnikow extern double dps_sound_lvl; extern double rcs_sound_lvl; /*--------------------------------------------------------------- FUNKCJE ---------------------------------------------------------------*/ //inicjalizuj dzwiek void init_sound(); //odtwarzaj dzwiek void make_sound(); //dzwiek eksplozji void crash_sound(); #endif
dagothar/apollo
apollo/simulink/r_rtwin/r_types.h
/* * r_types.h * * Real-Time Workshop code generation for Simulink model "r.mdl". * * Model version : 1.180 * Real-Time Workshop version : 7.5 (R2010a) 25-Jan-2010 * C source code generated on : Sun Jul 17 16:28:22 2011 * * Target selection: rtwin.tlc * Note: GRT includes extra infrastructure and instrumentation for prototyping * Embedded hardware selection: Generic->32-bit x86 compatible * Code generation objectives: Unspecified * Validation result: Not run */ #ifndef RTW_HEADER_r_types_h_ #define RTW_HEADER_r_types_h_ #include "rtwtypes.h" /* Parameters (auto storage) */ typedef struct Parameters_r_ Parameters_r; /* Forward declaration for rtModel */ typedef struct RT_MODEL_r RT_MODEL_r; #endif /* RTW_HEADER_r_types_h_ */
dagothar/apollo
src/control.h
#ifndef _CONTROL_H #define _CONTROL_H #include "main.h" #include "map.h" #include "log.h" #include "msg.h" /*--------------------------------------------------------------- ZMIENNE ---------------------------------------------------------------*/ //sterowanie WSADem extern bool WSAD_flag; //0 - steruje ladownikem, 1 - steruje kamera //tryb sterowania enum SteeringType { ROT, TRANS }; //tryby RCS extern SteeringType steering; //sterowania extern double w_main; //sterowanie glownym silnikiem extern double w_space; //sterowanie od spacji //parametry edycji zmiennych Simulinka const double sim_p_inc = 1.0; const double sim_p_log = 1.1; extern bool sim_p_mode; //tryb edycji: 0-inkrementalny, 1-logarytmiczny extern unsigned short sim_p; //wybrany do edycji parametr Simulinka /*--------------------------------------------------------------- FUNKCJE ---------------------------------------------------------------*/ //obsluga klawiatury - zarejestruj wcisniecie klawisza void keydown(unsigned char key, int x, int y); //tutaj sterowanie wejsc bistabilnych //obsluga klawiatury - zarejestruj puszczenie klawisza void keyup(unsigned char key, int x, int y); //obsluga klawiatury - klawisze specjalne void spcdown(int key, int x, int y); void spcup(int key, int x, int y); //obsluga wejscia od uzytkownika void ctrl(); //sterowanie wejsc monostabilnych #endif
dagothar/apollo
src/display.h
#ifndef _DISPLAY_H #define _DISPLAY_H #include <GL/glut.h> #include "main.h" #include "init.h" #include "hud.h" #include "lander.h" #include "simulink.h" #include "sound.h" /*--------------------------------------------------------------- PARAMETRY OKNA I KAMERY ---------------------------------------------------------------*/ //parametry okna graficznego const double fov = 45; const int screenw = 800; const int screenh = 600; //stale kamery const double camera_angle_per_sec = 30.0; const double camera_initial_distance = 50.0; const double camera_initial_height = 3.0; const double camera_initial_pitch = 0.0; const double camera_initial_yaw = 0.0; //pozycja kamery extern Vector c_pos; extern double camera_pitch; extern double camera_yaw; //tryb kamery extern bool camera_mode; //0 - fpp, 1 - tpp const double text_scale = 0.2; //skala tekstu void * const text_font = GLUT_BITMAP_HELVETICA_12; //czcionka zwykla void * const text_big_font = GLUT_BITMAP_HELVETICA_18; //czcionka duza /*--------------------------------------------------------------- ZMIENNE ---------------------------------------------------------------*/ //modele extern Model stack_model; //caly ladownik extern Model aps_model; //czlon aps extern Model dps_model; //czlon dps extern unsigned long frames; //ilosc klatek w sumie extern double fps; //ilosc klatek na sekunde //czy pokazac wektory sil itp. extern bool show_vectors; //okno kamery dodatkowej extern bool show_aux_cam; //sciezka ruchu ladownika na ekranie const double path_dt = 0.5; //co ile sekund dodawac nowy segment const int max_path = 250; //ile krokow zapamietac maksymalnie extern bool mark_path; //czy rysowac extern double last_path; //czas ostatniego dodania segmentu /*--------------------------------------------------------------- FUNKCJE ---------------------------------------------------------------*/ //glowna funkcja wyswietlania void display(); //wypisuje tekst na ekran void glutPrint(double x0, double y0, double scale, void *font, std::string text); //resetuj kamere void reset_camera(); //wyswietla sciezke ladownika //void Lander::draw_path(); //wyswietla slad na ziemi //void Lander::draw_shadow(); //wyswietla wektory predkosci itp. //void Lander::draw_vectors(); //wyswietla wektory predkosci itp. w trybie fpp //void Lander::draw_vectors_fpp(); //wyswietla obraz z kamery dodatkowej //void Lander::display_cam(); #endif
dagothar/apollo
src/vectors.h
<filename>src/vectors.h<gh_stars>0 #ifndef _VEC_H #define _VEC_H #include <cmath> #include "model.h" struct Quaternion; struct Vector { double x, y, z; Vector(); Vector(const Vector &v); Vector(const Quaternion &q); Vector(const double _x, const double _y, const double _z); Vector &operator=(const Vector &v); Vector &operator=(const Quaternion &q); Vector &operator+=(const Vector &v); Vector &operator-=(const Vector &v); Vector &operator*=(const double &f); Vector &operator/=(const double &f); bool operator==(const Vector &v) const; bool operator!=(const Vector &v) const; Vector operator+(const Vector &v) const; Vector operator-(const Vector &v) const; Vector operator*(const double f) const; Vector operator*(const Vector &v) const; Vector operator*(const Quaternion &q) const; Vertex to_vertex(); Vector &normalise(); double magnitude() const; //friend Vector operator-(const Vector &v); }; //Vector operator-(const Vector &v); typedef float Matrix[16]; struct Quaternion { double x, y, z, w; Quaternion(); Quaternion(const Quaternion &q); Quaternion(const Vector &v); Quaternion(double _x, double _y, double _z, double _w); Quaternion &operator=(const Quaternion &q); Quaternion &operator=(const Vector &v); Quaternion &operator+=(const Quaternion &q); Quaternion &operator-=(const Quaternion &q); Quaternion &operator*=(const double &f); Quaternion &operator/=(const double &f); Quaternion operator+(const Quaternion &q) const; Quaternion operator-(const Quaternion &q) const; Quaternion operator*(const Quaternion &q) const; Vector operator*(const Vector &v) const; Quaternion operator*(const double f) const; Quaternion &from_axis(const Vector &axis, double angle); Quaternion &from_euler(double pitch, double yaw, double roll); Vector to_euler() const; void to_matrix(Matrix m) const; Quaternion &normalise(); Quaternion get_conjugate() const; }; // przelicz stopnie na radiany double deg_to_rad(double angle); // przelicz radiany na stopnie double rad_to_deg(double angle); #endif
dagothar/apollo
apollo/simulink/autopilot_rtwin/rtmodel.h
<reponame>dagothar/apollo /* * rtmodel.h: * * Real-Time Workshop code generation for Simulink model "autopilot.mdl". * * Model version : 1.184 * Real-Time Workshop version : 7.5 (R2010a) 25-Jan-2010 * C source code generated on : Tue Jul 19 19:43:27 2011 * * Target selection: rtwin.tlc * Note: GRT includes extra infrastructure and instrumentation for prototyping * Embedded hardware selection: Generic->32-bit x86 compatible * Code generation objectives: Unspecified * Validation result: Not run */ #ifndef RTW_HEADER_rtmodel_h_ #define RTW_HEADER_rtmodel_h_ /* * Includes the appropriate headers when we are using rtModel */ #include "autopilot.h" #endif /* RTW_HEADER_rtmodel_h_ */
MistEO/meojson
include/json_exception.h
#pragma once #include <exception> #include <string> namespace json { class exception : public std::exception { public: exception() = default; exception(const std::string& msg); exception(const exception&) = default; exception& operator=(const exception&) = default; exception(exception&&) = default; exception& operator=(exception&&) = default; virtual ~exception() noexcept override = default; virtual const char* what() const noexcept override; private: std::string m_msg; }; } // namespace json