GPIO操作

  1. GPIO_InitTypeDef GPIO_Initure;
  2. __HAL_RCC_GPIOA_CLK_ENABLE();
  3. __HAL_RCC_GPIOB_CLK_ENABLE();
  4. GPIO_Initure.Pin=GPIO_PIN_13|GPIO_PIN_14|GPIO_PIN_15; //PG12 CLK
  5. GPIO_Initure.Mode=GPIO_MODE_OUTPUT_PP;//推挽输出
  6. GPIO_Initure.Pull=GPIO_PULLUP; //上拉
  7. GPIO_Initure.Speed=GPIO_SPEED_FREQ_VERY_HIGH;
  8. HAL_GPIO_Init(GPIOA,&GPIO_Initure);
  9. //PB3,4,7,8,9
  10. GPIO_Initure.Pin=GPIO_PIN_7;
  11. HAL_GPIO_Init(GPIOB,&GPIO_Initure);//???

定时

  1. void delay_us(uint16_t us)
  2. {
  3. uint16_t differ=0xffff-us-5;
  4. HAL_TIM_Base_Start(&htim5);
  5. __HAL_TIM_SetCounter(&htim5,differ);
  6. while(differ < 0xffff-5)
  7. {
  8. differ = __HAL_TIM_GetCounter(&htim5);
  9. }
  10. HAL_TIM_Base_Stop(&htim5);
  11. }
  12. void delay_ms(uint16_t nms)
  13. {
  14. uint16_t i;
  15. for(i=0;i<nms;i++) delay_us(1000);
  16. }

串口

1. use microlib

  1. 用前提!!!: 勾选use microlib
  2. //重定义fputc函数 F1/F4
  3. int fputc(int ch, FILE *f)
  4. {
  5. while((USART1->SR&0X40)==0);//循环发送,直到发送完毕
  6. USART1->DR = (uint8_t) ch;
  7. return ch;
  8. }
  9. //重定义fputc函数 F7/H7
  10. int fputc(int ch, FILE *f)
  11. {
  12. while((USART3->ISR&0X40)==0);//循环发送,直到发送完毕
  13. USART3->TDR=(uint8_t)ch;
  14. return ch;
  15. }

2. 不用microlib

  1. #if 1
  2. #pragma import(__use_no_semihosting)
  3. //标准库需要的支持函数
  4. struct __FILE
  5. {
  6. int handle;
  7. };
  8. FILE __stdout;
  9. //定义_sys_exit()以避免使用半主机模式
  10. void _sys_exit(int x)
  11. {
  12. x = x;
  13. }
  14. //重定义fputc函数
  15. int fputc(int ch, FILE *f)
  16. {
  17. while((USART3->ISR&0X40)==0);//循环发送,直到发送完毕
  18. USART3->TDR=ch;
  19. return ch;
  20. }
  21. #endif

3. simple way

  1. #include <stdio.h>
  2. #ifdef __GNUC__
  3. #define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
  4. #else
  5. #define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
  6. #endif
  7. PUTCHAR_PROTOTYPE
  8. {
  9. HAL_UART_Transmit(&huart3,(uint8_t*)&ch, 1, 0xFFFF);
  10. return ch;
  11. }
  1. uint8_t RxBuff[1]; //进入中断接收数据的数组
  2. uint8_t DataBuff[100]; //保存接收到的数据的数组
  3. int RxLine=0; //接收到的数据长度
  4. void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart){
  5. if(huart->Instance==USART1){
  6. RxLine++; //每接收到一个数据,进入回调数据长度加1
  7. DataBuff[RxLine-1]=RxBuff[0]; //把每次接收到的数据保存到缓存数组
  8. if(RxBuff[0]=='$') //接收结束标志位,这个数据可以自定义,根据实际需求,这里只做示例使用,不一定是0xff
  9. {
  10. printf("%s \r\n",DataBuff);
  11. uint8_t i;
  12. for(i=0;i<RxLine;i++){
  13. if(DataBuff[i]==
  14. }
  15. memset(DataBuff,0,sizeof(DataBuff)); //清空缓存数组
  16. RxLine=0; //清空接收长度
  17. }
  18. RxBuff[0]=0;
  19. HAL_UART_Receive_IT(&huart1, (uint8_t *)RxBuff, 1); //每接收一个数据,就打开一次串口中断接收,否则只会接收一个数据就停止接收
  20. }
  21. }