Why C++ is Rarely Used for Microcontroller Development
Preparation Work
Explanation
#ifdef __cplusplus extern "C" {#endif
// C source code here
#ifdef __cplusplus}#endif
Defining the LED Class
class LED_Class{}
class LED_Class{private: GPIO_TypeDef *GPIOx; uint16_t GPIO_Pin; uint32_t RCC_APB2Periph;}
class LED_Class{private: GPIO_TypeDef *GPIOx; uint16_t GPIO_Pin; uint32_t RCC_APB2Periph;
public: LED_Class(GPIO_TypeDef *GPIOx,uint16_t GPIO_Pin, uint32_t RCC_APB2Periph){ LED_Class::GPIOx = GPIOx; LED_Class::GPIO_Pin = GPIO_Pin; LED_Class::RCC_APB2Periph = RCC_APB2Periph; }
void Init(void){ GPIO_InitTypeDef GPIO_InitStruct;
RCC_APB2PeriphClockCmd(RCC_APB2Periph, ENABLE); GPIO_InitStruct.GPIO_Pin = GPIO_Pin; GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz; GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_Init(GPIOx, &GPIO_InitStruct); }
void Open(void){ GPIO_SetBits(GPIOx, GPIO_Pin); }
void Close(void){ GPIO_ResetBits(GPIOx, GPIO_Pin); }};
Implementation of Flashing Lights (main function)
int main(void){ LED_Class LED1(GPIOF, GPIO_Pin_7, RCC_APB2Periph_GPIOF); LED_Class LED2(GPIOF, GPIO_Pin_8, RCC_APB2Periph_GPIOF);
LED1.Init(); LED2.Init();
while(1) { LED1.Open(); LED2.Open(); Delay(10);
LED1.Close(); LED2.Close(); Delay(10); }}
int main(void){ LED_Class *LED1 = new LED_Class(GPIOF, GPIO_Pin_7, RCC_APB2Periph_GPIOF); LED_Class *LED2 = new LED_Class(GPIOF, GPIO_Pin_8, RCC_APB2Periph_GPIOF);
LED1->Init(); LED2->Init();
while(1) { LED1->Open(); LED2->Open(); Delay(50);
LED1->Close(); LED2->Close(); Delay(50); }}
Leave a Comment
Your email address will not be published. Required fields are marked *