'초보의 아웅다웅 설계하기/STM32'에 해당되는 글 51건

  1. 2019.11.17 STM32F723 UART LL_DRIVER 예제
  2. 2019.11.10 STM32H743 LL_Driver Timer
  3. 2019.11.09 STM32H743 UART LL_Driver 예제
  4. 2019.11.04 Intel-Hex 프로토콜 구조
  5. 2019.09.30 SPI Slave에서 입력 데이터 처리
  6. 2019.07.28 Multi Lun 사용시 설정 - Cube 사용시
  7. 2019.07.27 STM Cube 예제에서 USB Device MSC에서 저장공간을 RAM으로 잡고 사용하기
  8. 2019.07.08 CKS32F103 => STM의 카피캣을 만나다.
  9. 2019.07.02 STM Custom HID 보드로 입력되는 값 4Byte로 수정하기
  10. 2019.06.28 J-Link를 사용하여 MCU내 라이팅되어 있는 메모리 확인하기
  11. 2019.06.04 ST의 디자인 툴
  12. 2019.05.25 STM32L4 UART/LPUART LL_DRIVER
  13. 2019.05.25 STM32L4 SPI LL_DRIVER
  14. 2019.03.21 Keil 자동완성 기능 끄기
  15. 2019.03.02 PID 제어
  16. 2019.03.01 LSM6DSL, LIS2MDL, LPS22HB
  17. 2018.12.20 Base Timer 인터럽트 사용 안하고 설정하기 (1)
  18. 2018.12.06 STM32F Sleep Mode에서 Uart로 Wakeup하기
  19. 2018.10.22 SoftUart Only TX (2)
  20. 2018.10.16 24LC1025 데이터 Read, Write
  21. 2018.09.01 OLED QG-2864KSWLG01 내부 펌프 초기 코드
  22. 2018.08.17 Partial Erase Done (areas with no algorithms skipped!) 에러 발생
  23. 2018.08.17 고정위치에 바이너리 라이팅하기
  24. 2018.08.16 IAR Debugger 다운로드 설정
  25. 2018.07.27 LCD 5*8 픽셀 글자
  26. 2018.07.23 Tamper 사용
  27. 2018.07.23 다중 이동식 저장장치
  28. 2018.07.22 USB Composite
  29. 2018.07.18 error C1189: #error : MFC does not support WINVER less than 0x0501.
  30. 2018.07.16 Buzzer Melody
2019.11.17 20:10

뭘 좀 잘못한 걸까요? F723이 H743보다 더 빠르다니 이해가 잘 안되네요.

하지만 STM32F103이 STM32F091보다 연산이 느린걸 보면 그럴수도 있다고 생각이 되기도 하네요.(내부 플래쉬 메모리 접근 구조나 이런 차이일까요? 아님 캐쉬를 안 돌렸나? 확인 안해봤으니 상상의 나래만 ㅋㅋ큐ㅠㅠㅠ)

USB HS PHY가 안에 들어있어서 써볼까 생각했었는데 더 잘 되었네요. 다만 UFBGA나 WLCSP 타입이라서 아트웍이나 PCB 제작 후 수삽할 때 짜증이.... ㅠㅠ 

 

STM32F446 - 225DMIPS - ARIA 128, CBC Mode

Data Length - 32 byte
61 us
Data Length - 64 byte
100 us
Data Length - 128 byte
177 us
Data Length - 256 byte
331 us

Data Length - 512 byte

639 us

 

STM32H743 - 1027DMIPS - ARIA 128, CBC Mode

Data Length - 512 byte

393 us

 

STM32F723 - 462DMIPS - ARIA 128, CBC Mode

Data Length - 512 byte

237 us

 

그 외 키 길이별 속도 측정)

STM32F446 - 225DMIPS - ARIA 192, CBC Mode

Data Length - 512 byte

735 us

 

STM32F446 - 225DMIPS - ARIA 256, CBC Mode

Data Length - 512 byte

824 us



void Init_UART(uint8_t a_chUart, uint32_t a_nBaud)

  if(a_chUart == USART_1)
  {
/* (1) Enable GPIO clock and configures the USART pins *********************/

/* Enable the peripheral clock of GPIO Port */
LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_GPIOA);

/* Configure Tx Pin as : Alternate function, High Speed, Push pull, Pull up */
LL_GPIO_SetPinMode(GPIOA, LL_GPIO_PIN_9, LL_GPIO_MODE_ALTERNATE);
LL_GPIO_SetAFPin_8_15(GPIOA, LL_GPIO_PIN_9, LL_GPIO_AF_7);
LL_GPIO_SetPinSpeed(GPIOA, LL_GPIO_PIN_9, LL_GPIO_SPEED_FREQ_HIGH);
LL_GPIO_SetPinOutputType(GPIOA, LL_GPIO_PIN_9, LL_GPIO_OUTPUT_PUSHPULL);
LL_GPIO_SetPinPull(GPIOA, LL_GPIO_PIN_9, LL_GPIO_PULL_UP);

/* Configure Rx Pin as : Alternate function, High Speed, Push pull, Pull up */
LL_GPIO_SetPinMode(GPIOA, LL_GPIO_PIN_10, LL_GPIO_MODE_ALTERNATE);
LL_GPIO_SetAFPin_8_15(GPIOA, LL_GPIO_PIN_10, LL_GPIO_AF_7);
LL_GPIO_SetPinSpeed(GPIOA, LL_GPIO_PIN_10, LL_GPIO_SPEED_FREQ_HIGH);
LL_GPIO_SetPinOutputType(GPIOA, LL_GPIO_PIN_10, LL_GPIO_OUTPUT_PUSHPULL);
LL_GPIO_SetPinPull(GPIOA, LL_GPIO_PIN_10, LL_GPIO_PULL_UP);

/* (2) NVIC Configuration for USART interrupts */
/*  - Set priority for USARTx_IRQn */
/*  - Enable USARTx_IRQn */
NVIC_SetPriority(USART1_IRQn, 2);  
NVIC_EnableIRQ(USART1_IRQn);

/* (3) Enable USART peripheral clock and clock source ***********************/
LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_USART1);

/* Set clock source */
LL_RCC_SetUSARTClockSource(LL_RCC_USART1_CLKSOURCE_PCLK2);

/* (4) Configure USART functional parameters ********************************/

/* Disable USART prior modifying configuration registers */
/* Note: Commented as corresponding to Reset value */
// LL_USART_Disable(USART1);

/* TX/RX direction */
LL_USART_SetTransferDirection(USART1, LL_USART_DIRECTION_TX_RX);

/* 8 data bit, 1 start bit, 1 stop bit, no parity */
LL_USART_ConfigCharacter(USART1, LL_USART_DATAWIDTH_8B, LL_USART_PARITY_NONE, LL_USART_STOPBITS_1);

/* No Hardware Flow control */
/* Reset value is LL_USART_HWCONTROL_NONE */
LL_USART_SetHWFlowCtrl(USART1, LL_USART_HWCONTROL_NONE);

/* Oversampling by 16 */
/* Reset value is LL_USART_OVERSAMPLING_16 */
LL_USART_SetOverSampling(USART1, LL_USART_OVERSAMPLING_16);

/* Set Baudrate to 115200 using APB frequency set to 32000000 Hz */
/* Frequency available for USART peripheral can also be calculated through LL RCC macro */
/* Ex :
Periphclk = LL_RCC_GetUSARTClockFreq(Instance); or LL_RCC_GetUARTClockFreq(Instance); depending on USART/UART instance

In this example, Peripheral Clock is expected to be equal to 32000000 Hz => equal to SystemCoreClock
*/
LL_USART_SetBaudRate(USART1, SystemCoreClock/APB_Div, LL_USART_OVERSAMPLING_16, a_nBaud); 

/* (5) Enable USART *********************************************************/
LL_USART_Enable(USART1);

while((!(LL_USART_IsActiveFlag_TEACK(USART1))))

}
/* Enable RXNE and Error interrupts */
LL_USART_EnableIT_RXNE(USART1);
LL_USART_EnableIT_ERROR(USART1);

UART1_ClearBuf();
  }
  else if(a_chUart == USART_2){
/* (1) Enable GPIO clock and configures the USART pins *********************/

/* Enable the peripheral clock of GPIO Port */
LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_GPIOA);

/* Configure Tx Pin as : Alternate function, High Speed, Push pull, Pull up */
LL_GPIO_SetPinMode(GPIOA, LL_GPIO_PIN_2, LL_GPIO_MODE_ALTERNATE);
LL_GPIO_SetAFPin_0_7(GPIOA, LL_GPIO_PIN_2, LL_GPIO_AF_7);
LL_GPIO_SetPinSpeed(GPIOA, LL_GPIO_PIN_2, LL_GPIO_SPEED_FREQ_HIGH);
LL_GPIO_SetPinOutputType(GPIOA, LL_GPIO_PIN_2, LL_GPIO_OUTPUT_PUSHPULL);
LL_GPIO_SetPinPull(GPIOA, LL_GPIO_PIN_2, LL_GPIO_PULL_UP);

/* Configure Rx Pin as : Alternate function, High Speed, Push pull, Pull up */
LL_GPIO_SetPinMode(GPIOA, LL_GPIO_PIN_3, LL_GPIO_MODE_ALTERNATE);
LL_GPIO_SetAFPin_0_7(GPIOA, LL_GPIO_PIN_3, LL_GPIO_AF_7);
LL_GPIO_SetPinSpeed(GPIOA, LL_GPIO_PIN_3, LL_GPIO_SPEED_FREQ_HIGH);
LL_GPIO_SetPinOutputType(GPIOA, LL_GPIO_PIN_3, LL_GPIO_OUTPUT_PUSHPULL);
LL_GPIO_SetPinPull(GPIOA, LL_GPIO_PIN_3, LL_GPIO_PULL_UP);

/* (2) NVIC Configuration for USART interrupts */
/*  - Set priority for USARTx_IRQn */
/*  - Enable USARTx_IRQn */
NVIC_SetPriority(USART2_IRQn, 2);  
NVIC_EnableIRQ(USART2_IRQn);

/* (3) Enable USART peripheral clock and clock source ***********************/
LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_USART2);

/* Set clock source */
LL_RCC_SetUSARTClockSource(LL_RCC_USART2_CLKSOURCE_PCLK1);

/* TX/RX direction */
LL_USART_SetTransferDirection(USART2, LL_USART_DIRECTION_TX_RX);

/* 8 data bit, 1 start bit, 1 stop bit, no parity */
LL_USART_ConfigCharacter(USART2, LL_USART_DATAWIDTH_8B, LL_USART_PARITY_NONE, LL_USART_STOPBITS_1);

/* No Hardware Flow control */
/* Reset value is LL_USART_HWCONTROL_NONE */
LL_USART_SetHWFlowCtrl(USART2, LL_USART_HWCONTROL_NONE);

/* Oversampling by 16 */
/* Reset value is LL_USART_OVERSAMPLING_16 */
LL_USART_SetOverSampling(USART2, LL_USART_OVERSAMPLING_16);

/* Set Boad Rate */
LL_USART_SetBaudRate(USART2, SystemCoreClock/APB_Div, LL_USART_OVERSAMPLING_16, a_nBaud); 

/* (5) Enable USART *********************************************************/
LL_USART_Enable(USART2);

while((!(LL_USART_IsActiveFlag_TEACK(USART2))))

}
/* Enable RXNE and Error interrupts */
LL_USART_EnableIT_RXNE(USART2);
LL_USART_EnableIT_ERROR(USART2);

UART2_ClearBuf();
  }
}

 

/*******************************************************************************
* Function Name : 
* Parameters    : None
* Return        : None
* Description   : 
*******************************************************************************/
void UART1_ClearBuf(void)
{
    Uart1.RxInCnt = 0;
    Uart1.RxOutCnt = 0;
}

/*******************************************************************************
* Function Name : u8 UART1_GetChar(char *data)
* Parameters    : 
* Return        : µ¥ÀÌŸ ¼ö½Å ¿©ºÎ(0: ¼ö½Å¹öÆÛ°¡ ºñ¾úÀ½, 1: ¼ö½Å¹öÆÛ¿¡ µ¥ÀÌŸ°¡ ÀÖÀ½)
* Description   : UART1·Î ¼ö½Å¹öÆÛ¿¡¼­ µ¥ÀÌŸ(1byte) °¡Á®¿À±â
*******************************************************************************/
uint8_t UART1_GetChar(char *data)
{
    if(Uart1.RxInCnt == Uart1.RxOutCnt) return 0;
    else *data = Uart1.RxBuf[Uart1.RxOutCnt];
    if(Uart1.RxOutCnt<RBUF_SIZE-1) Uart1.RxOutCnt++;
    else Uart1.RxOutCnt = 0;

    return 1;
}

/*******************************************************************************
* Function Name : void UART1_PutChar(char data)
* Parameters    : ¾Æ½ºÅ°ÄÚµå
* Return        : None
* Description   : UART1 1¹®ÀÚ Ãâ·Â
*******************************************************************************/
void UART1_PutChar(uint8_t data)
{
// /* Wait for TXE flag to be raised */
// while (!LL_USART_IsActiveFlag_TXE(USART1));
// /* Write character in Transmit Data register.
// TXE flag is cleared by writing data in DR register */
// LL_USART_TransmitData8(USART1, data);
// /* Wait for TC flag to be raised for last char */
// while (!LL_USART_IsActiveFlag_TC(USART1));


/* Write character in Transmit Data register.
TXE flag is cleared by writing data in DR register */
LL_USART_TransmitData8(USART1, data);
/* Wait for TXE flag to be raised */
while (!LL_USART_IsActiveFlag_TXE(USART1));

}

/*******************************************************************************
* Function Name : 
* Parameters    : 
* Return        : None
* Description   :  
*******************************************************************************/
void UART1_PutStr(char *string)
{
while(*string != '\0') UART1_PutChar(*string++);
}

/*******************************************************************************
* Function Name : void UART1_Printf(const char *fmt,...)
* Parameters    : ¹®ÀÚ¿­ + ¼­½Ä
* Return        : none
* Description   : UART1 printf
*******************************************************************************/
void UART1_Printf(const char *fmt,...)
{
  char string[256];
  va_list ap;
  
  va_start(ap,fmt);
  vsprintf(string,fmt,ap);
  va_end(ap);
  
  UART1_PutStr(string);
}

/*******************************************************************************
* Function Name :  
* Parameters    : 
* Return        :
* Description   :  
void USARTx_IRQHandler(void)
{
  if(LL_USART_IsActiveFlag_RXNE(USART1) && LL_USART_IsEnabledIT_RXNE(USART1))
  {
    Callback_RX_USART1();
  }
  else
  {
    Error_Callback();
  }
}
*******************************************************************************/
void Callback_RX_USART1(void)
{
Uart1.RxBuf[Uart1.RxInCnt] = LL_USART_ReceiveData8(USART1);
/* ECHO mode Start */
// LL_USART_TransmitData8(USART1, Uart1.RxBuf[Uart1.RxInCnt]);
/* ECHO mode End */

if(Uart1.RxInCnt<RBUF_SIZE-1) Uart1.RxInCnt++;
else Uart1.RxInCnt = 0;
}

/*******************************************************************************
* Function Name : 
* Parameters    : None
* Return        : None
* Description   : 
*******************************************************************************/
static void UART2_ClearBuf(void)
{
    Uart2.RxInCnt = 0;
    Uart2.RxOutCnt = 0;
}

/*******************************************************************************
* Function Name : u8 UART1_GetChar(char *data)
* Parameters    : 
* Return        : µ¥ÀÌŸ ¼ö½Å ¿©ºÎ(0: ¼ö½Å¹öÆÛ°¡ ºñ¾úÀ½, 1: ¼ö½Å¹öÆÛ¿¡ µ¥ÀÌŸ°¡ ÀÖÀ½)
* Description   : UART1·Î ¼ö½Å¹öÆÛ¿¡¼­ µ¥ÀÌŸ(1byte) °¡Á®¿À±â
*******************************************************************************/
uint8_t UART2_GetChar(char *chpData)
{
    if(Uart2.RxInCnt == Uart2.RxOutCnt) return 0;
    else *chpData = Uart2.RxBuf[Uart2.RxOutCnt];
    if(Uart2.RxOutCnt<RBUF_SIZE-1) Uart2.RxOutCnt++;
    else Uart2.RxOutCnt = 0;

    return 1;
}

/*******************************************************************************
* Function Name : void UART1_PutChar(char data)
* Parameters    : ¾Æ½ºÅ°ÄÚµå
* Return        : None
* Description   : UART1 1¹®ÀÚ Ãâ·Â
*******************************************************************************/
void UART2_PutChar(uint8_t chData)
{
/* Write character in Transmit Data register.
TXE flag is cleared by writing data in DR register */
LL_USART_TransmitData8(USART2, chData);
/* Wait for TXE flag to be raised */
while (!LL_USART_IsActiveFlag_TXE(USART2));

}

/*******************************************************************************
* Function Name : 
* Parameters    : 
* Return        : None
* Description   :  
*******************************************************************************/
void UART2_PutStr(char *chpString)
{
while(*chpString != '\0') UART2_PutChar(*chpString++);
}

/*******************************************************************************
* Function Name : void UART2_Printf(const char *fmt,...)
* Parameters    : ¹®ÀÚ¿­ + ¼­½Ä
* Return        : none
* Description   : UART1 printf
*******************************************************************************/
void UART2_Printf(const char *fmt,...)
{
  char string[256];
  va_list ap;
  
  va_start(ap,fmt);
  vsprintf(string,fmt,ap);
  va_end(ap);
  
  UART2_PutStr(string);
}

/*******************************************************************************
* Function Name :  
* Parameters    : 
* Return        :
* Description   :  
void USARTx_IRQHandler(void)
{
  if(LL_USART_IsActiveFlag_RXNE(USART1) && LL_USART_IsEnabledIT_RXNE(USART1))
  {
    Callback_RX_USART1();
  }
  else
  {
    Error_Callback();
  }
}
*******************************************************************************/
void Callback_RX_USART2(void)
{
Uart2.RxBuf[Uart2.RxInCnt] = LL_USART_ReceiveData8(USART2);
 /* ECHO mode Start */
// LL_USART_TransmitData8(USART2, Uart2.RxBuf[Uart2.RxInCnt]);
 /* ECHO mode End */

 if(Uart2.RxInCnt<RBUF_SIZE-1) Uart2.RxInCnt++;
 else Uart2.RxInCnt = 0;
}

Posted by 초보 HW 엔지니어 로망와니

댓글을 달아 주세요

2019.11.10 09:34

분주하는 부분에서 약간 헤맸습니다.

 

 

/*******************************************************************************
* Function Name : 
* Parameters    : None
* Return        : None
* Description   : 
DEBUGPRINT("%d \r\n", SystemCoreClock);//400000000
*******************************************************************************/
void Config_TIM(void)
{
uint32_t Prescaler;
Prescaler = (uint32_t)(SystemCoreClock / (2*1000000)) - 1;

Init_Timer(eTimer2, 1000000, eInterruptEnable, Prescaler);
}

 

/*******************************************************************************
* Function Name : 
* Parameters    : None
* Return        : 
* Description   : 
*******************************************************************************/

int Init_Timer(const uint8_t a_chTimer, const uint32_t a_nUs, const InterruptEnableState a_chInt, const uint32_t a_nPrescaler)
{
/* Initial autoreload value */
if(a_nPrescaler > 65536){
return 1;
}
  
  if(a_chTimer == 1){
  }  
  else if(a_chTimer == 2){
/* Enable the timer peripheral clock */
LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_TIM2); 

/* Set counter mode */
/* Reset value is LL_TIM_COUNTERMODE_UP */
LL_TIM_SetCounterMode(TIM2, LL_TIM_COUNTERMODE_UP);

/* Set the pre-scaler value to have TIM2 counter clock equal to 10 kHz      */
LL_TIM_SetPrescaler(TIM2, a_nPrescaler);

// LL_TIM_SetClockDivision(TIM2, 64);

/* Set the auto-reload value to have an initial update event frequency of 10 Hz */
LL_TIM_SetAutoReload(TIM2, a_nUs);

    if(a_chInt == eInterruptEnable){
/* Enable the update interrupt */
LL_TIM_EnableIT_UPDATE(TIM2);

/* Configure the NVIC to handle TIM2 update interrupt */
NVIC_SetPriority(TIM2_IRQn, 0);
NVIC_EnableIRQ(TIM2_IRQn);
}
/* Enable counter */
LL_TIM_EnableCounter(TIM2);

/* Force update generation */
LL_TIM_GenerateEvent_UPDATE(TIM2);
  }

return 0;

}

Posted by 초보 HW 엔지니어 로망와니

댓글을 달아 주세요

2019.11.09 23:56

STM32H7 시리즈의 LL_Driver 예제를 찾아봐도 보이지 않았습니다.

예제는 COMP, DAC, RTC, SPI만 있어서 직접 만들었습니다.

약간의 삽질을 했습니다.

LL_USART_SetBaudRate함수에 분주까지 들어가서 헤맸네요.......

암호모듈 속도 측정결과 뭔가 획기적으로 속도가 빨라지지는 않네요. DMIPS 차이로는 거즘 4배인데 연산속도 차이는 2배가 채 안되어서 약간 실망감이 드네요.

 

STM32F446 - 225DMIPS - ARIA 128, CBC Mode

Data Length - 32 byte
61 us
Data Length - 64 byte
100 us
Data Length - 128 byte
177 us
Data Length - 256 byte
331 us

Data Length - 512 byte

639 us

 

STM32H743 - 1027DMIPS - ARIA 128, CBC Mode

Data Length - 512 byte

393 us

 

그 외 키 길이별 속도 측정)

STM32F446 - 225DMIPS - ARIA 192, CBC Mode

Data Length - 512 byte

735 us

 

STM32F446 - 225DMIPS - ARIA 256, CBC Mode

Data Length - 512 byte

824 us

 

 

#include "usr_usart.h"

#include  <stdarg.h>
#include  <stdio.h>

#include "stm32h7xx_ll_bus.h"
#include "stm32h7xx_ll_rcc.h"
#include "stm32h7xx_ll_gpio.h"
#include "stm32h7xx_ll_usart.h"

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro ------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
tUart Uart6;

/* Private function prototypes ------------------------------------------------*/
/* Private functions ---------------------------------------------------------*/

/*******************************************************************************
* Function Name : 
* Parameters    : None
* Return        : None
* Description   : 
*******************************************************************************/
void Config_UART(void)
{
Init_UART(USART_6, BAUDRATE_115200);
}

/*******************************************************************************
* Function Name : void Init_UART(uint8_t a_chUart,uint32_t baud)
* Parameters    : Åë½ÅÆ÷Æ®. Åë½Å¼Óµµ
* Return        : None
* Description   : UART ÃʱâÈ­
*******************************************************************************/
void Init_UART(uint8_t a_chUart, uint32_t a_nBaud)

  if(a_chUart == USART_1) {
  }
  else if(a_chUart == USART_2){
  }
  else if(a_chUart == USART_6)
  {
/* (1) Enable GPIO clock and configures the USART pins *********************/

/* Enable the peripheral clock of GPIO Port */
LL_AHB4_GRP1_EnableClock(LL_AHB4_GRP1_PERIPH_GPIOC);

/* Configure Tx Pin as : Alternate function, High Speed, Push pull, Pull up */
LL_GPIO_SetPinMode(GPIOC, LL_GPIO_PIN_6, LL_GPIO_MODE_ALTERNATE);
LL_GPIO_SetAFPin_0_7(GPIOC, LL_GPIO_PIN_6, LL_GPIO_AF_7);
LL_GPIO_SetPinSpeed(GPIOC, LL_GPIO_PIN_6, LL_GPIO_SPEED_FREQ_HIGH);
LL_GPIO_SetPinOutputType(GPIOC, LL_GPIO_PIN_6, LL_GPIO_OUTPUT_PUSHPULL);
LL_GPIO_SetPinPull(GPIOC, LL_GPIO_PIN_6, LL_GPIO_PULL_UP);

/* Configure Rx Pin as : Alternate function, High Speed, Push pull, Pull up */
LL_GPIO_SetPinMode(GPIOC, LL_GPIO_PIN_7, LL_GPIO_MODE_ALTERNATE);
LL_GPIO_SetAFPin_0_7(GPIOC, LL_GPIO_PIN_7, LL_GPIO_AF_7);
LL_GPIO_SetPinSpeed(GPIOC, LL_GPIO_PIN_7, LL_GPIO_SPEED_FREQ_HIGH);
LL_GPIO_SetPinOutputType(GPIOC, LL_GPIO_PIN_7, LL_GPIO_OUTPUT_PUSHPULL);
LL_GPIO_SetPinPull(GPIOC, LL_GPIO_PIN_7, LL_GPIO_PULL_UP);

/* (2) NVIC Configuration for USART interrupts */
/*  - Set priority for USARTx_IRQn */
/*  - Enable USARTx_IRQn */
NVIC_SetPriority(USART6_IRQn, 2);  
NVIC_EnableIRQ(USART6_IRQn);

/* (3) Enable USART peripheral clock and clock source ***********************/
LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_USART6);

/* Set clock source */
LL_RCC_SetUSARTClockSource(LL_RCC_USART16_CLKSOURCE_PCLK2);

/* (4) Configure USART functional parameters ********************************/

/* Disable USART prior modifying configuration registers */
/* Note: Commented as corresponding to Reset value */
LL_USART_Disable(USART6);

/* TX/RX direction */
LL_USART_SetTransferDirection(USART6, LL_USART_DIRECTION_TX_RX);

/* 8 data bit, 1 start bit, 1 stop bit, no parity */
LL_USART_ConfigCharacter(USART6, LL_USART_DATAWIDTH_8B, LL_USART_PARITY_NONE, LL_USART_STOPBITS_1);

// LL_USART_SetDataWidth(USART6, LL_USART_DATAWIDTH_8B);
// LL_USART_SetParity(USART6, LL_USART_PARITY_NONE);
// LL_USART_SetStopBitsLength(USART6, LL_USART_STOPBITS_1);
//
/* No Hardware Flow control */
/* Reset value is LL_USART_HWCONTROL_NONE */
LL_USART_SetHWFlowCtrl(USART6, LL_USART_HWCONTROL_NONE);

/* Oversampling by 16 */
/* Reset value is LL_USART_OVERSAMPLING_16 */
LL_USART_SetOverSampling(USART6, LL_USART_OVERSAMPLING_16);

/* Set Baudrate to 115200 using APB frequency set to 32000000 Hz */
/* Frequency available for USART peripheral can also be calculated through LL RCC macro */
/* Ex :
Periphclk = LL_RCC_GetUSARTClockFreq(Instance); or LL_RCC_GetUARTClockFreq(Instance); depending on USART/UART instance

In this example, Peripheral Clock is expected to be equal to 32000000 Hz => equal to SystemCoreClock
*/
LL_USART_SetBaudRate(USART6, SystemCoreClock, LL_USART_PRESCALER_DIV4, LL_USART_OVERSAMPLING_16, a_nBaud); 

/* (5) Enable USART *********************************************************/
LL_USART_Enable(USART6);

while((!(LL_USART_IsActiveFlag_TEACK(USART6))) || (!(LL_USART_IsActiveFlag_REACK(USART6))))

}
/* Enable RXNE and Error interrupts */
LL_USART_EnableIT_RXNE(USART6);
LL_USART_EnableIT_ERROR(USART6);

ClearBuf_UART6();
  }
}


/*******************************************************************************
* Function Name : 
* Parameters    : None
* Return        : None
* Description   : 
*******************************************************************************/
void ClearBuf_UART6(void)
{
    Uart6.RxInCnt = 0;
    Uart6.RxOutCnt = 0;
}

/*******************************************************************************
* Function Name : u8 GetChar_Uart6(char *data)
* Parameters    : 
* Return        : µ¥ÀÌŸ ¼ö½Å ¿©ºÎ(0: ¼ö½Å¹öÆÛ°¡ ºñ¾úÀ½, 1: ¼ö½Å¹öÆÛ¿¡ µ¥ÀÌŸ°¡ ÀÖÀ½)
* Description   : Uart6·Î ¼ö½Å¹öÆÛ¿¡¼­ µ¥ÀÌŸ(1byte) °¡Á®¿À±â
*******************************************************************************/
uint8_t GetChar_Uart6(char *data)
{
    if(Uart6.RxInCnt == Uart6.RxOutCnt) return MH_EMPTY;
    else *data = Uart6.RxBuf[Uart6.RxOutCnt];
    if(Uart6.RxOutCnt<RBUF_SIZE-1) Uart6.RxOutCnt++;
    else Uart6.RxOutCnt = 0;

    return MH_RECEIVED;
}

/*******************************************************************************
* Function Name : void PutChar_Uart6(char data)
* Parameters    : ¾Æ½ºÅ°ÄÚµå
* Return        : None
* Description   : Uart6 1¹®ÀÚ Ãâ·Â
*******************************************************************************/
void PutChar_Uart6(uint8_t data)
{
/* Write character in Transmit Data register.
TXE flag is cleared by writing data in DR register */
USART6->TDR = data;
/* Wait for TXE flag to be raised */
while (!LL_USART_IsActiveFlag_TXE(USART6));
}

/*******************************************************************************
* Function Name : 
* Parameters    : 
* Return        : None
* Description   :  
*******************************************************************************/
void PutStr_Uart6(char *string)
{
while(*string != '\0') PutChar_Uart6(*string++);
}

/*******************************************************************************
* Function Name : void Printf_Uart6(const char *fmt,...)
* Parameters    : ¹®ÀÚ¿­ + ¼­½Ä
* Return        : none
* Description   : Uart6 printf
*******************************************************************************/
void Printf_UART6(const char *fmt,...)
{
  char string[256];
  va_list ap;
  
  va_start(ap,fmt);
  vsprintf(string,fmt,ap);
  va_end(ap);
  
  PutStr_Uart6(string);
}

/*******************************************************************************
* Function Name :  
* Parameters    : 
* Return        :
* Description   :  
void USARTx_IRQHandler(void)
{
  if(LL_USART_IsActiveFlag_RXNE(USART6) && LL_USART_IsEnabledIT_RXNE(USART6))
  {
    Callback_RX_USART6();
  }
  else
  {
    Error_Callback();
  }
}
*******************************************************************************/
void Callback_RX_USART6(void)
{
Uart6.RxBuf[Uart6.RxInCnt] = LL_USART_ReceiveData8(USART6);
/* ECHO mode Start */
// LL_USART_TransmitData8(USART6, Uart6.RxBuf[Uart6.RxInCnt]);
/* ECHO mode End */

if(Uart6.RxInCnt<RBUF_SIZE-1) Uart6.RxInCnt++;
else Uart6.RxInCnt = 0;
}

Posted by 초보 HW 엔지니어 로망와니

댓글을 달아 주세요

2019.11.04 14:06

keil로 컴파일하고 나니 나온 Address Offset 데이터가 위아래로 섞여 있어서 난리였습니다.

차근차근 일정한 패턴을 가지고 Address Offset가 순차로 내려갈 줄 알았는데 위, 아래, 위위, 아래 난리네요.

다운로드 프로그램을 만드는데 전부 확인해서 조립한 다음 일정 바이트씩 쪼개서 내려줘야하니 이것도 참 문제네요.

 

 

--- Intel-Hex 프로토콜 구조 ---

STX : 1byte(:)

Length : 1byte

Address Offset : 2byte

Type : 1byte

Data : 0 ~ 255byte

CheckSum : 1byte

 

 

예제)

:09 6D59 00 7D027F487E600265F7 AF
:10 6B0F 00 7D047F487E601265F77F467E601265FE CA
:0B 6B1F 00 8F3FE4FD7F467E600265F7 BB

.......

 

:03 000B 00 02530B 92
.......


:08 6A6A 00 4207C2950EBE08EA C6
:01 6A72 00 22 01
......

 

:05 000E 00 126CC17F06 29
:08 0013 00 C293126A5AD29322 33

......

:0E 6267 00 7A81798C7B01908140E0FCA3E0FD 00

:0B 6275 00 9081B2EBF0A3EAF0A3E9F0 87

Posted by 초보 HW 엔지니어 로망와니

댓글을 달아 주세요

2019.09.30 15:25

사용 MCU : STM32L432



SPI Slave Mode에서 입력된 데이터를 파싱하고 처리하는 데도 연달아 데이터가 계속 들어오다보니 어느순간 SPI가 죽어버렸습니다. (SPI Flash의 쓰기 같은 경우 데이터를 넣고 나서 완료되었는 지 Status 값을 확인하기 위해 SPI에 데이터를 계속 넣는데 그런 경우를 가정하였습니다. - 사용중에 MCU의 Reset를 하도록 회로설계가 되면되지만 그렇지 못한 경우도 가정해야하니까요.)

어디선가 충돌이 나고 있는데... 들어온 데이터의 암복호화 연산처리중에 죽는건지(Stack도 충분한데) 사실 파악은 하지 못하였으나 일단 다 연산하기 전에 셋다 disable 해주고 나서 처리 후 enable 해주니까 괜찮네요... 안 괜찮네요. 

원인 파악을 확실히 못했으니 나중에 또 문제가 발생할 여지가 있네요.
답답.. 일단 다른 게 더 급하니 패스하고 나중에 다시 봐야겠습니다.

원인을 알았습니다.

보내는 부분에서 데이터가 다 보내질 때까지 while로 레지스터가 비워졌는지 체크하는데 Master에서 데이터를 밀어주지 않으니 못 보내고 뻗네요.(ST의 hal 예제로 Master을 구현하고 Slave는 전송이랑 수신의 데이터 길이가 다르게 설계)

입출력 길이를 맞춰주도록 설계를 바꾸고(ST 예제만 가지고 구현하는 사람들을 위해서...) 출력할 때 Timeout넣어주고 했습니다.

 

=> 다른 문제가 하나 더 있었네요. 보드를 두개 연결해서 사용했는데 전원을 Slave를 먼저 켜는 경우 데이터가 밀려서 그랬네요. Master 먼저 켜주고 Slave를 켜주니 괜찮았습니다.



/* Disable RXE   Interrupt             */ 
LL_SPI_DisableIT_RXNE(SPI1); 
/* Disble Error Interrupt             */ 
LL_SPI_DisableIT_ERR(SPI1);



Get_Data();  => SPI 데이터 처리

/* Enable TXE   Interrupt             */ 
LL_SPI_EnableIT_TXE(SPI1); 

Put_Data();  => SPI데이터 출력


/* Enable RXE   Interrupt             */ 
LL_SPI_EnableIT_RXNE(SPI1); 
/* Disable TXE   Interrupt             */ 
LL_SPI_DisableIT_TXE(SPI1); 
/* Enable Error Interrupt             */ 
LL_SPI_EnableIT_ERR(SPI1);

 
Posted by 초보 HW 엔지니어 로망와니

댓글을 달아 주세요

2019.07.28 09:32

/* Includes ------------------------------------------------------------------*/
#include "usbd_storage.h"

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
#define STORAGE_LUN_NBR 2
#define STORAGE_BLK_NBR 64 //256 blocks * 512 = 128k
#define STORAGE_BLK_SIZ 512 //doesn't seem to work well with values other than 512
#define STORAGE_CAPACITY (STORAGE_BLK_NBR * STORAGE_BLK_SIZ)

#define WAIT_TIMEOUT                                        5000



/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* USB Mass storage Standard Inquiry Data */
int8_t STORAGE_Inquirydata[] = { /* 36 */
  /* LUN 0 */
  0x00,
  0x80,
  0x02,
  0x02,
  (STANDARD_INQUIRY_DATA_LEN - 5),
  0x00,
  0x00,
  0x00,
  'S', 'T', 'M', ' ', ' ', ' ', ' ', ' ', /* Manufacturer: 8 bytes  */
  'P', 'r', 'o', 'd', 'u', 'c', 't', ' ', /* Product     : 16 Bytes */
  ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
  '0', '.', '0','1',                      /* Version     : 4 Bytes  */
  /* LUN 1 */
  0x00,
  0x80,
  0x02,
  0x02,
  (STANDARD_INQUIRY_DATA_LEN - 5),
  0x00,
  0x00,
  0x00,
  'S', 'T', 'M', ' ', ' ', ' ', ' ', ' ', /* Manufacturer: 8 bytes  */
  'P', 'r', 'o', 'd', 'u', 'c', 't', ' ', /* Product     : 16 Bytes */
  ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
  '0', '.', '0','1',                      /* Version     : 4 Bytes  */
};

extern USBD_HandleTypeDef USBD_Device;

/* Private function prototypes -----------------------------------------------*/
int8_t STORAGE_Init(uint8_t lun);
int8_t STORAGE_GetCapacity(uint8_t lun, uint32_t *block_num, uint16_t *block_size);
int8_t STORAGE_IsReady(uint8_t lun);
int8_t STORAGE_IsWriteProtected(uint8_t lun);
int8_t STORAGE_Read(uint8_t lun, uint8_t *buf, uint32_t blk_addr, uint16_t blk_len);
int8_t STORAGE_Write(uint8_t lun, uint8_t *buf, uint32_t blk_addr, uint16_t blk_len);
int8_t STORAGE_GetMaxLun(void);

USBD_StorageTypeDef USBD_DISK_fops = {
  STORAGE_Init,
  STORAGE_GetCapacity,
  STORAGE_IsReady,
  STORAGE_IsWriteProtected,
  STORAGE_Read,
  STORAGE_Write,
  STORAGE_GetMaxLun,
  STORAGE_Inquirydata,
};
/* Private functions ---------------------------------------------------------*/

#define FLASH_USER_START_ADDR   ADDR_FLASH_SECTOR_6 /* Start @ of user Flash area */
#define FLASH_USER_END_ADDR     ADDR_FLASH_SECTOR_6 + GetSectorSize(ADDR_FLASH_SECTOR_6) -1 /* End @ of user Flash area : sector start address + sector size -1 */

#define ADDR_FLASH_SECTOR_0     ((uint32_t)0x08000000) /* Base address of Sector 0, 16 Kbytes */
#define ADDR_FLASH_SECTOR_1     ((uint32_t)0x08004000) /* Base address of Sector 1, 16 Kbytes */
#define ADDR_FLASH_SECTOR_2     ((uint32_t)0x08008000) /* Base address of Sector 2, 16 Kbytes */
#define ADDR_FLASH_SECTOR_3     ((uint32_t)0x0800C000) /* Base address of Sector 3, 16 Kbytes */
#define ADDR_FLASH_SECTOR_4     ((uint32_t)0x08010000) /* Base address of Sector 4, 64 Kbytes */
#define ADDR_FLASH_SECTOR_5     ((uint32_t)0x08020000) /* Base address of Sector 5, 128 Kbytes */
#define ADDR_FLASH_SECTOR_6     ((uint32_t)0x08040000) /* Base address of Sector 6, 128 Kbytes */
#define ADDR_FLASH_SECTOR_7     ((uint32_t)0x08060000) /* Base address of Sector 7, 128 Kbytes */

static uint32_t GetSector(uint32_t Address);

/**
  * @brief  Initializes the storage unit (medium)
  * @param  lun: Logical unit number
  * @retval Status (0 : OK / -1 : Error)
  */
int8_t STORAGE_Init(uint8_t lun)
{
switch(lun){
case 0:
break;
case 1:
break;
case 2:
break;
default:
return (USBD_FAIL);
}    
  return (USBD_OK);
}

/**
  * @brief  Returns the medium capacity.
  * @param  lun: Logical unit number
  * @param  block_num: Number of total block number
  * @param  block_size: Block size
  * @retval Status (0: OK / -1: Error)
  */
int8_t STORAGE_GetCapacity(uint8_t lun, uint32_t *block_num, uint16_t *block_size)
{
switch(lun){
case 0:
*block_num  = STORAGE_BLK_NBR;
*block_size = STORAGE_BLK_SIZ;
break;
case 1:
*block_num  = STORAGE_BLK_NBR;
*block_size = STORAGE_BLK_SIZ;
break;
case 2:
*block_num  = STORAGE_BLK_NBR;
*block_size = STORAGE_BLK_SIZ;
break;
default:
return (USBD_FAIL);
}    
  return (USBD_OK);
}

/**
  * @brief  Checks whether the medium is ready.
  * @param  lun: Logical unit number
  * @retval Status (0: OK / -1: Error)
  */
int8_t STORAGE_IsReady(uint8_t lun)
{
switch(lun){
case 0:
break;
case 1:
break;
case 2:
break;
default:
return (USBD_FAIL);

  return (USBD_OK);
}

/**
  * @brief  Checks whether the medium is write protected.
  * @param  lun: Logical unit number
  * @retval Status (0: write enabled / -1: otherwise)
  */
int8_t STORAGE_IsWriteProtected(uint8_t lun)
{
// Uart2_printf("STORAGE_IsWriteProtected\r\n");
switch(lun){
case 0:
break;
case 1:
break;
case 2:
break;
default:
return (USBD_FAIL);

  return (USBD_OK);
}

/**
  * @brief  Reads data from the medium.
  * @param  lun: Logical unit number
  * @param  blk_addr: Logical block address
  * @param  blk_len: Blocks number
  * @retval Status (0: OK / -1: Error)
  */
int8_t STORAGE_Read(uint8_t lun, uint8_t *buf, uint32_t blk_addr, uint16_t blk_len)
{
  uint32_t i, j;

switch(lun){
case 0:
break;
case 1:
break;
case 2:
break;
default:
return (USBD_FAIL);
}    
return (USBD_OK);
}

/**
  * @brief  Writes data into the medium.
  * @param  lun: Logical unit number
  * @param  blk_addr: Logical block address
  * @param  blk_len: Blocks number
  * @retval Status (0 : OK / -1 : Error)
  */
int8_t STORAGE_Write(uint8_t lun, uint8_t *buf, uint32_t blk_addr, uint16_t blk_len)
{
switch(lun){
case 0:
break;
case 1:
break;
case 2:
break;
default:
return (USBD_FAIL);
}
return (USBD_OK);
}

/**
  * @brief  Returns the Max Supported LUNs.
  * @param  None
  * @retval Lun(s) number
  */
int8_t STORAGE_GetMaxLun(void)
{
  return(STORAGE_LUN_NBR - 1);
}

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

Posted by 초보 HW 엔지니어 로망와니

댓글을 달아 주세요

2019.07.27 23:17

 


/* Includes ------------------------------------------------------------------*/
#include "usbd_storage.h"

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
#define STORAGE_LUN_NBR 1
#define STORAGE_BLK_NBR 64 //64 blocks * 512 = 32k
#define STORAGE_BLK_SIZ 512 //doesn't seem to work well with values other than 512
#define STORAGE_CAPACITY (STORAGE_BLK_NBR * STORAGE_BLK_SIZ)

#define WAIT_TIMEOUT                                        5000

uint8_t usbMassStorage[STORAGE_BLK_NBR][STORAGE_BLK_SIZ];


/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* USB Mass storage Standard Inquiry Data */
int8_t STORAGE_Inquirydata[] = { /* 36 */
  /* LUN 0 */
  0x00,
  0x80,
  0x02,
  0x02,
  (STANDARD_INQUIRY_DATA_LEN - 5),
  0x00,
  0x00,
  0x00,
  'S', 'T', 'M', ' ', ' ', ' ', ' ', ' ', /* Manufacturer: 8 bytes  */
  'P', 'r', 'o', 'd', 'u', 'c', 't', ' ', /* Product     : 16 Bytes */
  ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
  '0', '.', '0','1',                      /* Version     : 4 Bytes  */
};

extern USBD_HandleTypeDef USBD_Device;

/* Private function prototypes -----------------------------------------------*/
int8_t STORAGE_Init(uint8_t lun);
int8_t STORAGE_GetCapacity(uint8_t lun, uint32_t *block_num, uint16_t *block_size);
int8_t STORAGE_IsReady(uint8_t lun);
int8_t STORAGE_IsWriteProtected(uint8_t lun);
int8_t STORAGE_Read(uint8_t lun, uint8_t *buf, uint32_t blk_addr, uint16_t blk_len);
int8_t STORAGE_Write(uint8_t lun, uint8_t *buf, uint32_t blk_addr, uint16_t blk_len);
int8_t STORAGE_GetMaxLun(void);

USBD_StorageTypeDef USBD_DISK_fops = {
  STORAGE_Init,
  STORAGE_GetCapacity,
  STORAGE_IsReady,
  STORAGE_IsWriteProtected,
  STORAGE_Read,
  STORAGE_Write,
  STORAGE_GetMaxLun,
  STORAGE_Inquirydata,
};
/* Private functions ---------------------------------------------------------*/
/**
  * @brief  Initializes the storage unit (medium)
  * @param  lun: Logical unit number
  * @retval Status (0 : OK / -1 : Error)
  */
int8_t STORAGE_Init(uint8_t lun)
{
  return (USBD_OK);
}

/**
  * @brief  Returns the medium capacity.
  * @param  lun: Logical unit number
  * @param  block_num: Number of total block number
  * @param  block_size: Block size
  * @retval Status (0: OK / -1: Error)
  */
int8_t STORAGE_GetCapacity(uint8_t lun, uint32_t *block_num, uint16_t *block_size)
{
  *block_num  = STORAGE_BLK_NBR;
  *block_size = STORAGE_BLK_SIZ;

  return (USBD_OK);
}

/**
  * @brief  Checks whether the medium is ready.
  * @param  lun: Logical unit number
  * @retval Status (0: OK / -1: Error)
  */
int8_t STORAGE_IsReady(uint8_t lun)
{
  return (USBD_OK);
}

/**
  * @brief  Checks whether the medium is write protected.
  * @param  lun: Logical unit number
  * @retval Status (0: write enabled / -1: otherwise)
  */
int8_t STORAGE_IsWriteProtected(uint8_t lun)
{
  return (USBD_OK);
}

/**
  * @brief  Reads data from the medium.
  * @param  lun: Logical unit number
  * @param  blk_addr: Logical block address
  * @param  blk_len: Blocks number
  * @retval Status (0: OK / -1: Error)
  */
int8_t STORAGE_Read(uint8_t lun, uint8_t *buf, uint32_t blk_addr, uint16_t blk_len)
{
  uint32_t i, j;

switch(lun){
case 0:
for (i = 0; i < blk_len; i++){
for(j = 0; j < STORAGE_BLK_SIZ; j++){//512
buf[j] = usbMassStorage[(i + blk_addr)][j];
}
}
break;
case 1:
break;
default:
return (USBD_FAIL);
}    
return (USBD_OK);
}

/**
  * @brief  Writes data into the medium.
  * @param  lun: Logical unit number
  * @param  blk_addr: Logical block address
  * @param  blk_len: Blocks number
  * @retval Status (0 : OK / -1 : Error)
  */
int8_t STORAGE_Write(uint8_t lun, uint8_t *buf, uint32_t blk_addr, uint16_t blk_len)
{
uint8_t i = 0;
uint16_t j = 0;

switch(lun){
case 0:
for (i = 0; i < blk_len; i++){
for(j = 0; j < STORAGE_BLK_SIZ; j++){//512
usbMassStorage[(i + blk_addr)][j] = buf[j + (i*STORAGE_BLK_SIZ)];
}
}
case 1:
break;
default:
return (USBD_FAIL);
}
return (USBD_OK);
}

/**
  * @brief  Returns the Max Supported LUNs.
  * @param  None
  * @retval Lun(s) number
  */
int8_t STORAGE_GetMaxLun(void)
{
  return(STORAGE_LUN_NBR - 1);
}

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/

 

Posted by 초보 HW 엔지니어 로망와니

댓글을 달아 주세요

2019.07.08 16:48

 

저가에 IO가 크게 필요없는 제품을 개발하기 위해서 보다보니 약 3000원의 STM32F103 제품이 보였습니다. PCB 뜨고 이러면 비싸니 바로 구매하였습니다.

며칠 지나니 택배가 똭!!

근데 어라? 머 이상하네? 테스트하려고 보니 CKS32F103C8T6.. 말로만 들었던 중국 카피캣 제품이 !!! - 사이트에 STM32라면서요?

혹시나 하고 STM으로 프로그램을 짠 후 ST-Link와 ST Utility를 사용하여 라이팅했더니 정상 동작 두둥....

신뢰성은 괜찮은걸까? 사용해도 되는 걸까? 하는 의구심은 있지만 일단 사용... (테스트는 USB와 Led만 깜빡거려보았습니다.) 항상 놀라지만 중국의 카피 능력은 진짜 대단하네요. 

 

시스템 개발 보드 단일 칩 코어 STM32 ARM STM32F103

http://www.11st.co.kr/product/SellerProductDetail.tmall?method=getSellerProductDetail&prdNo=2280181952&gclid=CjwKCAjw9dboBRBUEiwA7VrrzTvopjqWRSJjDf8gT087JcNd28wN73vZIqfccW1a8wqx-NHcban_GxoCK88QAvD_BwE&utm_term=&utm_campaign=%B1%B8%B1%DB%BC%EE%C7%CEPC+%C3%DF%B0%A1%C0%DB%BE%F7&utm_source=%B1%B8%B1%DB_PC_S_%BC%EE%C7%CE&utm_medium=%B0%CB%BB%F6

 

시스템 개발 보드 단일 칩 코어 STM32 ARM STM32F103 - 11번가

배송정보 안내 - 도착정보는 최근 배송데이터 기반으로 분석하여 예측된 기준으로 노출됩니다. - 판매자가 설정하지 않았거나, 내부기준으로 일부 노출이 안될수도 있습니다. - 판매자/택배사 사정으로 발송,도착, 택배사 정보가 변동 될 수 있습니다. 레이어 닫기

www.11st.co.kr

 

 

Posted by 초보 HW 엔지니어 로망와니

댓글을 달아 주세요

2019.07.02 17:06

STM Custom HID 보드로 입력되는 값 4Byte로 수정하기

선언을 TX라고 했지만 실제 in, out은 PC를 기준으로 하기때문에 PC의 out이 보드에서는 in입니다.

 

#define MAXPCKRXSIZE 0x02
#define MAXPCKTXSIZE 0x04


/* USB Configuration Descriptor */
/*   All Descriptors (Configuration, Interface, Endpoint, Class, Vendor */
const uint8_t CustomHID_ConfigDescriptor[CUSTOMHID_SIZ_CONFIG_DESC] =
  {
    0x09, /* bLength: Configuation Descriptor size */
    USB_CONFIGURATION_DESCRIPTOR_TYPE, /* bDescriptorType: Configuration */
    CUSTOMHID_SIZ_CONFIG_DESC,
    /* wTotalLength: Bytes returned */
    0x00,
    0x01,         /* bNumInterfaces: 1 interface */
    0x01,         /* bConfigurationValue: Configuration value */
    0x00,         /* iConfiguration: Index of string descriptor describing
                                 the configuration*/
    0xC0,         /* bmAttributes: Bus powered */
    0x32,         /* MaxPower 100 mA: this current is used for detecting Vbus */

    /************** Descriptor of Custom HID interface ****************/
    /* 09 */
    0x09,         /* bLength: Interface Descriptor size */
    USB_INTERFACE_DESCRIPTOR_TYPE,/* bDescriptorType: Interface descriptor type */
    0x00,         /* bInterfaceNumber: Number of Interface */
    0x00,         /* bAlternateSetting: Alternate setting */
    0x02,         /* bNumEndpoints */
    0x03,         /* bInterfaceClass: HID */
    0x00,         /* bInterfaceSubClass : 1=BOOT, 0=no boot */
    0x00,         /* nInterfaceProtocol : 0=none, 1=keyboard, 2=mouse */
    0,            /* iInterface: Index of string descriptor */
    /******************** Descriptor of Custom HID HID ********************/
    /* 18 */
    0x09,         /* bLength: HID Descriptor size */
    HID_DESCRIPTOR_TYPE, /* bDescriptorType: HID */
    0x10,         /* bcdHID: HID Class Spec release number */
    0x01,
    0x00,         /* bCountryCode: Hardware target country */
    0x01,         /* bNumDescriptors: Number of HID class descriptors to follow */
    0x22,         /* bDescriptorType */
    CUSTOMHID_SIZ_REPORT_DESC,/* wItemLength: Total length of Report descriptor */
    0x00,
    /******************** Descriptor of Custom HID endpoints ******************/
    /* 27 */
    0x07,          /* bLength: Endpoint Descriptor size */
    USB_ENDPOINT_DESCRIPTOR_TYPE, /* bDescriptorType: */

    0x81,          /* bEndpointAddress: Endpoint Address (IN) */
    0x03,          /* bmAttributes: Interrupt endpoint */
    MAXPCKRXSIZE,          /* wMaxPacketSize: 2 Bytes max */
    0x00,
    0x20,          /* bInterval: Polling Interval (32 ms) */
    /* 34 */
    
    0x07, /* bLength: Endpoint Descriptor size */
    USB_ENDPOINT_DESCRIPTOR_TYPE, /* bDescriptorType: */
/* Endpoint descriptor type */
    0x01, /* bEndpointAddress: */
/* Endpoint Address (OUT) */
    0x03, /* bmAttributes: Interrupt endpoint */
    MAXPCKTXSIZE, /* wMaxPacketSize: 4 Bytes max  */
    0x00,
    0x20, /* bInterval: Polling Interval (20 ms) */
    /* 41 */
  }

 

const uint8_t CustomHID_ReportDescriptor[CUSTOMHID_SIZ_REPORT_DESC] =
  {    
    0x05, 0x8c,            /* USAGE_PAGE (ST Page)           */                   
    0x09, 0x01,            /* USAGE (Demo Kit)               */    
    0xa1, 0x01,            /* COLLECTION (Application)       */            
    /* 6 */
    
    /* Led 1 */        
    0x85, 0x01,            /*     REPORT_ID (1)      */
    0x09, 0x01,            /*     USAGE (LED 1)              */
    0x15, 0x00,            /*     LOGICAL_MINIMUM (0)        */          
    0x25, 0x02,            /*     LOGICAL_MAXIMUM (1)        */           
    0x75, 0x08,            /*     REPORT_SIZE (8)            */        
    0x95, (MAXPCKTXSIZE -1),            /*     REPORT_COUNT (3)           */       
    0xB1, 0x82,             /*    FEATURE (Data,Var,Abs,Vol) */     

    0x85, 0x01,            /*     REPORT_ID (1)              */
    0x09, 0x01,            /*     USAGE (LED 1)              */
    0x91, 0x82,            /*     OUTPUT (Data,Var,Abs,Vol)  */
    /* 26 */
    
    /* Led 2 */
    0x85, 0x02,            /*     REPORT_ID 2      */
    0x09, 0x02,            /*     USAGE (LED 2)              */
    0x15, 0x00,            /*     LOGICAL_MINIMUM (0)        */          
    0x25, 0x01,            /*     LOGICAL_MAXIMUM (1)        */           
    0x75, 0x08,            /*     REPORT_SIZE (8)            */        
    0x95, (MAXPCKTXSIZE -1),            /*     REPORT_COUNT (1)           */       
    0xB1, 0x82,             /*    FEATURE (Data,Var,Abs,Vol) */     

    0x85, 0x02,            /*     REPORT_ID (2)              */
    0x09, 0x02,            /*     USAGE (LED 2)              */
    0x91, 0x82,            /*     OUTPUT (Data,Var,Abs,Vol)  */
    /* 46 */
    
    /* Led 3 */        
    0x85, 0x03,            /*     REPORT_ID (3)      */
    0x09, 0x03,            /*     USAGE (LED 3)              */
    0x15, 0x00,            /*     LOGICAL_MINIMUM (0)        */          
    0x25, 0x01,            /*     LOGICAL_MAXIMUM (1)        */           
    0x75, 0x08,            /*     REPORT_SIZE (8)            */        
    0x95, (MAXPCKTXSIZE -1),            /*     REPORT_COUNT (3)           */       
    0xB1, 0x82,             /*    FEATURE (Data,Var,Abs,Vol) */     

    0x85, 0x03,            /*     REPORT_ID (3)              */
    0x09, 0x03,            /*     USAGE (LED 3)              */
    0x91, 0x82,            /*     OUTPUT (Data,Var,Abs,Vol)  */
    /* 66 */
    
    /* Led 4 */
    0x85, 0x04,            /*     REPORT_ID 4)      */
    0x09, 0x04,            /*     USAGE (LED 4)              */
    0x15, 0x00,            /*     LOGICAL_MINIMUM (0)        */          
    0x25, 0x01,            /*     LOGICAL_MAXIMUM (1)        */           
    0x75, 0x08,            /*     REPORT_SIZE (8)            */        
    0x95, (MAXPCKTXSIZE -1),            /*     REPORT_COUNT (3)           */       
    0xB1, 0x82,            /*     FEATURE (Data,Var,Abs,Vol) */     

    0x85, 0x04,            /*     REPORT_ID (4)              */
    0x09, 0x04,            /*     USAGE (LED 4)              */
    0x91, 0x82,            /*     OUTPUT (Data,Var,Abs,Vol)  */
    /* 86 */
    
    /* key Push Button */  
    0x85, 0x05,            /*     REPORT_ID (5)              */
    0x09, 0x05,            /*     USAGE (Push Button)        */      
    0x15, 0x00,            /*     LOGICAL_MINIMUM (0)        */      
    0x25, 0x01,            /*     LOGICAL_MAXIMUM (1)        */      
    0x75, 0x01,            /*     REPORT_SIZE (1)            */  
    0x81, 0x82,            /*     INPUT (Data,Var,Abs,Vol)   */   
    
    0x09, 0x05,            /*     USAGE (Push Button)        */               
    0x75, 0x01,            /*     REPORT_SIZE (1)            */           
    0xb1, 0x82,            /*     FEATURE (Data,Var,Abs,Vol) */  
         
    0x75, 0x07,            /*     REPORT_SIZE (7)            */           
    0x81, 0x83,            /*     INPUT (Cnst,Var,Abs,Vol)   */                    
    0x85, 0x05,            /*     REPORT_ID (5)              */         
                    
    0x75, 0x07,            /*     REPORT_SIZE (7)            */           
    0xb1, 0x83,            /*     FEATURE (Cnst,Var,Abs,Vol) */                      
    /* 114 */

    /* Tamper Push Button */  
    0x85, 0x06,            /*     REPORT_ID (6)              */
    0x09, 0x06,            /*     USAGE (Tamper Push Button) */      
    0x15, 0x00,            /*     LOGICAL_MINIMUM (0)        */      
    0x25, 0x01,            /*     LOGICAL_MAXIMUM (1)        */      
    0x75, 0x01,            /*     REPORT_SIZE (1)            */  
    0x81, 0x82,            /*     INPUT (Data,Var,Abs,Vol)   */   
    
    0x09, 0x06,            /*     USAGE (Tamper Push Button) */               
    0x75, 0x01,            /*     REPORT_SIZE (1)            */           
    0xb1, 0x82,            /*     FEATURE (Data,Var,Abs,Vol) */  
         
    0x75, 0x07,            /*     REPORT_SIZE (7)            */           
    0x81, 0x83,            /*     INPUT (Cnst,Var,Abs,Vol)   */                    
    0x85, 0x06,            /*     REPORT_ID (6)              */         
                    
    0x75, 0x07,            /*     REPORT_SIZE (7)            */           
    0xb1, 0x83,            /*     FEATURE (Cnst,Var,Abs,Vol) */  
    /* 142 */
    
    /* ADC IN */
    0x85, 0x07,            /*     REPORT_ID (7)              */         
    0x09, 0x07,            /*     USAGE (ADC IN)             */          
    0x15, 0x00,            /*     LOGICAL_MINIMUM (0)        */               
    0x26, 0xff, 0x00,      /*     LOGICAL_MAXIMUM (255)      */                 
    0x75, 0x08,            /*     REPORT_SIZE (8)            */           
    0x81, 0x82,            /*     INPUT (Data,Var,Abs,Vol)   */                    
    0x85, 0x07,            /*     REPORT_ID (7)              */                 
    0x09, 0x07,            /*     USAGE (ADC in)             */                     
    0xb1, 0x82,            /*     FEATURE (Data,Var,Abs,Vol) */                                 
    /* 161 */

    0xc0            /*     END_COLLECTION              */
  }; /* CustomHID_ReportDescriptor */

void CustomHID_Reset(void)
{
  /* Set Joystick_DEVICE as not configured */
  pInformation->Current_Configuration = 0;
  pInformation->Current_Interface = 0;/*the default Interface*/
  
  /* Current Feature initialization */
  pInformation->Current_Feature = CustomHID_ConfigDescriptor[7];
  
  SetBTABLE(BTABLE_ADDRESS);

  /* Initialize Endpoint 0 */
  SetEPType(ENDP0, EP_CONTROL);
  SetEPTxStatus(ENDP0, EP_TX_STALL);
  SetEPRxAddr(ENDP0, ENDP0_RXADDR);
  SetEPTxAddr(ENDP0, ENDP0_TXADDR);
  Clear_Status_Out(ENDP0);
  SetEPRxCount(ENDP0, Device_Property.MaxPacketSize);
  SetEPRxValid(ENDP0);

  /* Initialize Endpoint 1 */
  SetEPType(ENDP1, EP_INTERRUPT);
  SetEPTxAddr(ENDP1, ENDP1_TXADDR);
  SetEPRxAddr(ENDP1, ENDP1_RXADDR);
  SetEPTxCount(ENDP1, MAXPCKRXSIZE);
  SetEPRxCount(ENDP1, MAXPCKTXSIZE);
  SetEPRxStatus(ENDP1, EP_RX_VALID);
  SetEPTxStatus(ENDP1, EP_TX_NAK);

  bDeviceState = ATTACHED;
  
  /* Set this device to response on default address */
  SetDeviceAddress(0);
}

Posted by 초보 HW 엔지니어 로망와니

댓글을 달아 주세요

2019.06.28 23:57

1. J-Mem을 실행합니다.

 

 

2. 보고자 하는 MCU나 MCU의 Core를 선택합니다.

 

 

3. 보고싶은 메모리 번지를 Address에 적어 메모리의 내용을 확인합니다.

Posted by 초보 HW 엔지니어 로망와니

댓글을 달아 주세요

2019.06.04 08:31

ST사에서 웹으로 설계 프로그램을 지원하고 있습니다. 

NFC쪽을 그리다 안테나 설계를 안테나 회사에 다니는 친구에게 부탁을 할까하면서 구글링을 하다보니 ST에서 지원하는 것을 알게 되었습니다. 여러가지 설계 지원 툴 중 하나지만 제가 필요한 건 이거니까.

값을 변경해가면서 바로바로 결과를 알 수 있으니 좋습니다. 실제 PCB를 제작했을때도 동일하게 나올지는 잘 모르겠네요. 요즘 TI도 그렇고 ST도 그렇고 원하는 결과만 넣으면 값과 회로도까지 툭하고 튀어나오니 진짜 편하네요. 한편으로는 하드웨어 엔지니어인 제 자리가 위험하다는 생각이 드네요. 몇년뒤면 하드웨어 엔지니어는 없어지지 않을까 하는 걱정까지 듭니다. 펌웨어도 설정을 하면 기본 소스가 나오는 걸 보면 그 자리도 위험하긴 매한가지겠네요. 에휴 앞으로도 몇십년 더 벌어야 하는데... ㅠㅠ

 

https://my.st.com/analogsimulator/html/#/home

 

eDesignSuite (HTML5)

 

my.st.com

https://my.st.com/analogsimulator/html_app/antenna/#/

 

Antenna Design | eDesignSuite | STMicroelectronics

Unsupported Browser Dear User, this browser is not supported by this application. For best user experience we recommend to use an updated version of the most widely browsers like Chrome, Firefox.

my.st.com

 

안테나 디자인 페이지

Posted by 초보 HW 엔지니어 로망와니

댓글을 달아 주세요

2019.05.25 07:57

#include "stm32l4xx_ll_bus.h"
#include "stm32l4xx_ll_rcc.h"
#include "stm32l4xx_ll_gpio.h"
#include "stm32l4xx_ll_usart.h"

#include "stm32l4xx_ll_lpuart.h"

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro ------------------------------------------------------------*/

#define USART_1  1
#define USART_2  2
#define USART_3 3
#define USART_4 4

#define BAUDRATE_9600  9600
#define BAUDRATE_38400  38400
#define BAUDRATE_57600  57600
#define BAUDRATE_115200  115200


/* Private variables ---------------------------------------------------------*/
/* Private function prototypes ---------------------------------------------*/
/* Private functions ---------------------------------------------------------*/

/*******************************************************************************
* Function Name : 
* Parameters    : None
* Return        : None
* Description   : 
*******************************************************************************/
void Config_UART(void)
{
Init_UART(USART_1, BAUDRATE_115200);
Init_LPUART(USART_1, BAUDRATE_115200);
}

/*******************************************************************************
* Function Name : void Init_UART(uint8_t a_chUart,uint32_t baud)
* Parameters    : 통신포트. 통신속도
* Return        : None
* Description   : UART 초기화
*******************************************************************************/
void Init_UART(uint8_t a_chUart, uint32_t a_nBaud)
{
  if(a_chUart == 1){
/* (1) Enable GPIO clock and configures the USART pins *********************/

/* Enable the peripheral clock of GPIO Port */
LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_GPIOA);

/* Configure Tx Pin as : Alternate function, High Speed, Push pull, Pull up */
LL_GPIO_SetPinMode(GPIOA, LL_GPIO_PIN_9, LL_GPIO_MODE_ALTERNATE);
LL_GPIO_SetAFPin_8_15(GPIOA, LL_GPIO_PIN_9, LL_GPIO_AF_7);
LL_GPIO_SetPinSpeed(GPIOA, LL_GPIO_PIN_9, LL_GPIO_SPEED_FREQ_HIGH);
LL_GPIO_SetPinOutputType(GPIOA, LL_GPIO_PIN_9, LL_GPIO_OUTPUT_PUSHPULL);
LL_GPIO_SetPinPull(GPIOA, LL_GPIO_PIN_9, LL_GPIO_PULL_UP);

/* Configure Rx Pin as : Alternate function, High Speed, Push pull, Pull up */
LL_GPIO_SetPinMode(GPIOA, LL_GPIO_PIN_10, LL_GPIO_MODE_ALTERNATE);
LL_GPIO_SetAFPin_8_15(GPIOA, LL_GPIO_PIN_10, LL_GPIO_AF_7);
LL_GPIO_SetPinSpeed(GPIOA, LL_GPIO_PIN_10, LL_GPIO_SPEED_FREQ_HIGH);
LL_GPIO_SetPinOutputType(GPIOA, LL_GPIO_PIN_10, LL_GPIO_OUTPUT_PUSHPULL);
LL_GPIO_SetPinPull(GPIOA, LL_GPIO_PIN_10, LL_GPIO_PULL_UP);

/* (2) NVIC Configuration for USART interrupts */
/*  - Set priority for USARTx_IRQn */
/*  - Enable USARTx_IRQn */
NVIC_SetPriority(USART1_IRQn, 2);  
NVIC_EnableIRQ(USART1_IRQn);

/* (3) Enable USART peripheral clock and clock source ***********************/
LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_USART1);

/* Set clock source */
LL_RCC_SetUSARTClockSource(LL_RCC_USART1_CLKSOURCE_PCLK2);

/* TX/RX direction */
LL_USART_SetTransferDirection(USART1, LL_USART_DIRECTION_TX_RX);

/* 8 data bit, 1 start bit, 1 stop bit, no parity */
LL_USART_ConfigCharacter(USART1, LL_USART_DATAWIDTH_8B, LL_USART_PARITY_NONE, LL_USART_STOPBITS_1);

/* No Hardware Flow control */
/* Reset value is LL_USART_HWCONTROL_NONE */
LL_USART_SetHWFlowCtrl(USART1, LL_USART_HWCONTROL_NONE);

/* Oversampling by 16 */
/* Reset value is LL_USART_OVERSAMPLING_16 */
LL_USART_SetOverSampling(USART1, LL_USART_OVERSAMPLING_16);

/* Set Boad Rate */
LL_USART_SetBaudRate(USART1, SystemCoreClock, LL_USART_OVERSAMPLING_16, a_nBaud); 

/* (5) Enable USART *********************************************************/
LL_USART_Enable(USART1);

while((!(LL_USART_IsActiveFlag_TEACK(USART1))) || (!(LL_USART_IsActiveFlag_REACK(USART1))))

}
/* Enable RXNE and Error interrupts */
LL_USART_EnableIT_RXNE(USART1);
LL_USART_EnableIT_ERROR(USART1);

ClearBuf_UART1();
  }
  else if(a_chUart == 2){
  }
  else if(a_chUart == 3){
  }
  else if(a_chUart == 4){
#ifdef USE_USART4  
/* (1) Enable GPIO clock and configures the USART pins *********************/

/* Enable the peripheral clock of GPIO Port */
LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_GPIOC);

/* Configure Tx Pin as : Alternate function, High Speed, Push pull, Pull up */
LL_GPIO_SetPinMode(GPIOC, LL_GPIO_PIN_10, LL_GPIO_MODE_ALTERNATE);
LL_GPIO_SetAFPin_8_15(GPIOC, LL_GPIO_PIN_10, LL_GPIO_AF_8);
LL_GPIO_SetPinSpeed(GPIOC, LL_GPIO_PIN_10, LL_GPIO_SPEED_FREQ_HIGH);
LL_GPIO_SetPinOutputType(GPIOC, LL_GPIO_PIN_10, LL_GPIO_OUTPUT_PUSHPULL);
LL_GPIO_SetPinPull(GPIOC, LL_GPIO_PIN_10, LL_GPIO_PULL_UP);

/* Configure Rx Pin as : Alternate function, High Speed, Push pull, Pull up */
LL_GPIO_SetPinMode(GPIOC, LL_GPIO_PIN_11, LL_GPIO_MODE_ALTERNATE);
LL_GPIO_SetAFPin_8_15(GPIOC, LL_GPIO_PIN_11, LL_GPIO_AF_8);
LL_GPIO_SetPinSpeed(GPIOC, LL_GPIO_PIN_11, LL_GPIO_SPEED_FREQ_HIGH);
LL_GPIO_SetPinOutputType(GPIOC, LL_GPIO_PIN_11, LL_GPIO_OUTPUT_PUSHPULL);
LL_GPIO_SetPinPull(GPIOC, LL_GPIO_PIN_11, LL_GPIO_PULL_UP);

/* (2) NVIC Configuration for USART interrupts */
/*  - Set priority for USARTx_IRQn */
/*  - Enable USARTx_IRQn */
NVIC_SetPriority(UART4_IRQn, 2);  
NVIC_EnableIRQ(UART4_IRQn);

/* (3) Enable USART peripheral clock and clock source ***********************/
LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_UART4);

/* Set clock source */
LL_RCC_SetUSARTClockSource(LL_RCC_UART4_CLKSOURCE_PCLK1);

/* TX/RX direction */
LL_USART_SetTransferDirection(UART4, LL_USART_DIRECTION_TX_RX);

/* 8 data bit, 1 start bit, 1 stop bit, no parity */
LL_USART_ConfigCharacter(UART4, LL_USART_DATAWIDTH_8B, LL_USART_PARITY_NONE, LL_USART_STOPBITS_1);

/* No Hardware Flow control */
/* Reset value is LL_USART_HWCONTROL_NONE */
LL_USART_SetHWFlowCtrl(UART4, LL_USART_HWCONTROL_NONE);

/* Oversampling by 16 */
/* Reset value is LL_USART_OVERSAMPLING_16 */
LL_USART_SetOverSampling(UART4, LL_USART_OVERSAMPLING_16);

/* Set Boad Rate */
LL_USART_SetBaudRate(UART4, SystemCoreClock, LL_USART_OVERSAMPLING_16, a_nBaud); 

/* (5) Enable USART *********************************************************/
LL_USART_Enable(UART4);

while((!(LL_USART_IsActiveFlag_TEACK(UART4))) || (!(LL_USART_IsActiveFlag_REACK(UART4))))

}
/* Enable RXNE and Error interrupts */
LL_USART_EnableIT_RXNE(UART4);
LL_USART_EnableIT_ERROR(UART4);

ClearBuf_UART4();
#endif
  }
}

/*******************************************************************************
* Function Name : void Init_UART(uint8_t a_chUart,uint32_t baud)
* Parameters    : 통신포트. 통신속도
* Return        : None
* Description   : UART 초기화
*******************************************************************************/
void Init_LPUART(uint8_t a_chUart, uint32_t a_nBaud)
{
 
  if(a_chUart == 1){
/* (1) Enable GPIO clock and configures the LPUART1 pins *******************/
/*    (TX on PC.1, RX on PC.0)                        **********************/

/* Enable the peripheral clock of GPIOC */
LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_GPIOC);

/* Configure TX Pin as : Alternate function, High Speed, PushPull, Pull up */
LL_GPIO_SetPinMode(GPIOC, LL_GPIO_PIN_1, LL_GPIO_MODE_ALTERNATE);
LL_GPIO_SetAFPin_0_7(GPIOC, LL_GPIO_PIN_1, LL_GPIO_AF_8);
LL_GPIO_SetPinSpeed(GPIOC, LL_GPIO_PIN_1, LL_GPIO_SPEED_FREQ_HIGH);
LL_GPIO_SetPinOutputType(GPIOC, LL_GPIO_PIN_1, LL_GPIO_OUTPUT_PUSHPULL);
LL_GPIO_SetPinPull(GPIOC, LL_GPIO_PIN_1, LL_GPIO_PULL_NO);

/* Configure RX Pin as : Alternate function, High Speed, PushPull, Pull up */
LL_GPIO_SetPinMode(GPIOC, LL_GPIO_PIN_0, LL_GPIO_MODE_ALTERNATE);
LL_GPIO_SetAFPin_0_7(GPIOC, LL_GPIO_PIN_0, LL_GPIO_AF_8);
LL_GPIO_SetPinSpeed(GPIOC, LL_GPIO_PIN_0, LL_GPIO_SPEED_FREQ_HIGH);
LL_GPIO_SetPinOutputType(GPIOC, LL_GPIO_PIN_0, LL_GPIO_OUTPUT_PUSHPULL);
LL_GPIO_SetPinPull(GPIOC, LL_GPIO_PIN_0, LL_GPIO_PULL_NO);

/* (2) NVIC Configuration for LPUART1 interrupts */
/*  - Set priority for LPUART1_IRQn */
/*  - Enable LPUART1_IRQn           */
NVIC_SetPriority(LPUART1_IRQn, 0);  
NVIC_EnableIRQ(LPUART1_IRQn);

/* (3) Enable the LPUART1 peripheral clock and clock source ****************/
LL_APB1_GRP2_EnableClock(LL_APB1_GRP2_PERIPH_LPUART1);

/* Set LPUART1 clock source as HSI */
LL_RCC_SetLPUARTClockSource(LL_RCC_LPUART1_CLKSOURCE_PCLK1);// LL_RCC_SetLPUARTClockSource(LL_RCC_LPUART1_CLKSOURCE_HSI);

/* (4) Configure LPUART1 functional parameters ********************************/

/* Disable LPUART1 prior modifying configuration registers */
/* Note: Commented as corresponding to Reset value */
// LL_LPUART_Disable(LPUART1);

/* TX/RX direction */
LL_LPUART_SetTransferDirection(LPUART1, LL_LPUART_DIRECTION_TX_RX);

/* 8 data bit, 1 start bit, 1 stop bit, no parity */
LL_LPUART_ConfigCharacter(LPUART1, LL_LPUART_DATAWIDTH_8B, LL_LPUART_PARITY_NONE, LL_LPUART_STOPBITS_1);

/* No Hardware Flow control */
/* Reset value is LL_USART_HWCONTROL_NONE */
// LL_USART_SetHWFlowCtrl(LPUART1, LL_USART_HWCONTROL_NONE);

/* Set Baudrate to 9600 using HSI frequency set to HSI_VALUE */
LL_LPUART_SetBaudRate(LPUART1, SystemCoreClock, a_nBaud); // LL_LPUART_SetBaudRate(LPUART1, HSI_VALUE, a_nBaud); 

#ifdef USE_USARTWUFMODE 
/* Set the wake-up event type : specify wake-up on RXNE flag */
LL_LPUART_SetWKUPType(LPUART1, LL_LPUART_WAKEUP_ON_RXNE);
#endif

/* (5) Enable LPUART1 **********************************************************/
LL_LPUART_Enable(LPUART1);

while((!(LL_USART_IsActiveFlag_TEACK(LPUART1))) || (!(LL_USART_IsActiveFlag_REACK(LPUART1))))

}
/* Enable RXNE and Error interrupts */
LL_USART_EnableIT_RXNE(LPUART1);
LL_USART_EnableIT_ERROR(LPUART1);

ClearBuf_LPUART1();
  }
  else if(a_chUart == 2){
  }
  else if(a_chUart == 3){
  }
  else if(a_chUart == 4){
  }
}

'초보의 아웅다웅 설계하기 > STM32' 카테고리의 다른 글

J-Link를 사용하여 MCU내 라이팅되어 있는 메모리 확인하기  (0) 2019.06.28
ST의 디자인 툴  (0) 2019.06.04
STM32L4 UART/LPUART LL_DRIVER  (0) 2019.05.25
STM32L4 SPI LL_DRIVER  (0) 2019.05.25
Keil 자동완성 기능 끄기  (0) 2019.03.21
PID 제어  (0) 2019.03.02
Posted by 초보 HW 엔지니어 로망와니

댓글을 달아 주세요

2019.05.25 07:52

 

#include "string.h"

#include "usr_system.h"

#include "stm32l4xx_ll_bus.h"
#include "stm32l4xx_ll_rcc.h"
#include "stm32l4xx_ll_gpio.h"
#include "stm32l4xx_ll_spi.h"
#include "stm32l4xx_ll_dma.h"

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/

#define SPI_1  1 

#define SPI_2  2
#define SPI_3 3
#define SPI_4 4
#define SPI_5 5

#define SPI_MASTER LL_SPI_MODE_MASTER
#define SPI_SLAVE  LL_SPI_MODE_SLAVE

#define SPI1_NSS_PORT GPIOB
#define SPI1_NSS_PIN LL_GPIO_PIN_6
#define SPI1_SCK_PORT GPIOA
#define SPI1_SCK_PIN LL_GPIO_PIN_5
#define SPI1_MISO_PORT GPIOA
#define SPI1_MISO_PIN LL_GPIO_PIN_6
#define SPI1_MOSI_PORT GPIOA
#define SPI1_MOSI_PIN LL_GPIO_PIN_7

/* Defines -------------------------------------------------------------------*/
#define DUMMY_BYTE    0x00
#define SPI_FLAG_TIMEOUT 0x1000;
#define SPI_RXFLAG_TIMEOUT 0x1000;

#define SPIRBUF_SIZE       128


/* Private macro ------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
tSpi Spi1;

/* Private function prototypes ------------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
static void Init_SPI(uint8_t a_chSpi, uint32_t a_nMasterSlave, const InterruptEnableState a_chInt, const InterruptEnableState a_chDMA);
static void ClearBuf_SPI1(void);

/*******************************************************************************
* Function Name : 
* Parameters    : None
* Return        : None
* Description   : 
*******************************************************************************/
void Config_SPI(void)
{
Init_SPI(SPI_1, SPI_MASTER, eInterruptDisable, eInterruptDisable);
}

/*******************************************************************************
* Function Name : SPI_Init(uint8_t a_chSpi, uint32_t a_nMasterSlave)
* Description   :SPI 초기화, 반이중 방식일 경우 MOSI와 MISO를 크로스 해주어야 함.
* Parameters    : 통신포트. 마스터 슬레이브
* Return        : None
*******************************************************************************/
static void Init_SPI(uint8_t a_chSpi, uint32_t a_nMasterSlave, const InterruptEnableState a_chInt, const InterruptEnableState a_chDMA)

  if(a_chSpi == 1)
  {
/* (1) Enables GPIO clock and configures the SPI1 pins ********************/
/* Enable the peripheral clock of GPIOA */
LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_GPIOA);
/* Enable the peripheral clock of GPIOB */
LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_GPIOB);

/* Configure SCK Pin connected to pin 31 of CN12 connector */
LL_GPIO_SetPinMode(SPI1_SCK_PORT, SPI1_SCK_PIN, LL_GPIO_MODE_ALTERNATE);
LL_GPIO_SetAFPin_0_7(SPI1_SCK_PORT, SPI1_SCK_PIN, LL_GPIO_AF_5);
LL_GPIO_SetPinSpeed(SPI1_SCK_PORT, SPI1_SCK_PIN, LL_GPIO_SPEED_FREQ_VERY_HIGH);
LL_GPIO_SetPinPull(SPI1_SCK_PORT, SPI1_SCK_PIN, GPIO_NOPULL);//LL_GPIO_PULL_DOWN

/* Configure MISO Pin connected to pin 27 of CN12 connector */
LL_GPIO_SetPinMode(SPI1_MISO_PORT, SPI1_MISO_PIN, LL_GPIO_MODE_ALTERNATE);
LL_GPIO_SetAFPin_0_7(SPI1_MISO_PORT, SPI1_MISO_PIN, LL_GPIO_AF_5);
LL_GPIO_SetPinSpeed(SPI1_MISO_PORT, SPI1_MISO_PIN, LL_GPIO_SPEED_FREQ_VERY_HIGH);
LL_GPIO_SetPinPull(SPI1_MISO_PORT, SPI1_MISO_PIN, GPIO_NOPULL);//LL_GPIO_PULL_DOWN

/* Configure MOSI Pin connected to pin 29 of CN12 connector */
LL_GPIO_SetPinMode(SPI1_MOSI_PORT, SPI1_MOSI_PIN, LL_GPIO_MODE_ALTERNATE);
LL_GPIO_SetAFPin_0_7(SPI1_MOSI_PORT, SPI1_MOSI_PIN, LL_GPIO_AF_5);
LL_GPIO_SetPinSpeed(SPI1_MOSI_PORT, SPI1_MOSI_PIN, LL_GPIO_SPEED_FREQ_VERY_HIGH);
LL_GPIO_SetPinPull(SPI1_MOSI_PORT, SPI1_MOSI_PIN, GPIO_NOPULL);//LL_GPIO_PULL_DOWN

/* (3) Configure SPI1 functional parameters ********************************/

/* Enable the peripheral clock of GPIOA */
LL_APB2_GRP1_EnableClock(LL_APB2_GRP1_PERIPH_SPI1);

LL_SPI_SetStandard(SPI1, 0x00);
LL_SPI_SetClockPhase(SPI1, LL_SPI_PHASE_2EDGE);
LL_SPI_SetClockPolarity(SPI1, LL_SPI_POLARITY_LOW);
LL_SPI_SetBaudRatePrescaler(SPI1, LL_SPI_BAUDRATEPRESCALER_DIV16);
LL_SPI_SetTransferBitOrder(SPI1, LL_SPI_MSB_FIRST);
LL_SPI_SetTransferDirection(SPI1, LL_SPI_FULL_DUPLEX);
LL_SPI_SetDataWidth(SPI1, LL_SPI_DATAWIDTH_8BIT);
LL_SPI_SetRxFIFOThreshold(SPI1, LL_SPI_RX_FIFO_TH_QUARTER);

LL_SPI_SetCRCWidth(SPI1, 0x00);
LL_SPI_SetCRCPolynomial(SPI1, 7);
LL_SPI_DisableCRC(SPI1);
LL_SPI_DisableNSSPulseMgt(SPI1);
if(a_nMasterSlave == SPI_MASTER){
/* Configure CE Pin connected to pin 29 of CN10 connector */
LL_GPIO_SetPinMode(SPI1_NSS_PORT, SPI1_NSS_PIN, LL_GPIO_MODE_OUTPUT);
LL_GPIO_SetPinOutputType(SPI1_NSS_PORT, SPI1_NSS_PIN, LL_GPIO_OUTPUT_PUSHPULL);
LL_GPIO_SetPinSpeed(SPI1_NSS_PORT, SPI1_NSS_PIN, LL_GPIO_SPEED_FREQ_VERY_HIGH);
LL_GPIO_SetPinPull(SPI1_NSS_PORT, SPI1_NSS_PIN, LL_GPIO_PULL_NO);

LL_SPI_SetNSSMode(SPI1, LL_SPI_NSS_SOFT); //LL_SPI_NSS_HARD_INPUT
LL_SPI_SetMode(SPI1, LL_SPI_MODE_MASTER);
}
else if(a_nMasterSlave == SPI_SLAVE){
LL_GPIO_SetPinMode(SPI1_NSS_PORT, SPI1_NSS_PIN, LL_GPIO_MODE_ALTERNATE); //LL_GPIO_MODE_INPUT
LL_GPIO_SetPinSpeed(SPI1_NSS_PORT, SPI1_NSS_PIN, LL_GPIO_SPEED_FREQ_VERY_HIGH);
LL_GPIO_SetAFPin_8_15(SPI1_NSS_PORT, SPI1_NSS_PIN, LL_GPIO_AF_5);
LL_GPIO_SetPinPull(SPI1_NSS_PORT, SPI1_NSS_PIN, LL_GPIO_PULL_DOWN);

LL_SPI_SetNSSMode(SPI1, LL_SPI_NSS_HARD_INPUT); //LL_SPI_NSS_SOFT
LL_SPI_SetMode(SPI1, LL_SPI_MODE_SLAVE);
}

if(a_chDMA == eInterruptDisable){
if(a_chInt == eInterruptEnable){
/* (2) Configure NVIC for SPI1 transfer complete/error interrupts **********/
/* Set priority for SPI1_IRQn */
NVIC_SetPriority(SPI1_IRQn, 1);
/* Enable SPI1_IRQn           */
NVIC_EnableIRQ(SPI1_IRQn);

/* Configure SPI1 transfer interrupts */
/* Enable RXNE  Interrupt             */
LL_SPI_EnableIT_RXNE(SPI1);
/* Enable TXE   Interrupt             */
  LL_SPI_EnableIT_TXE(SPI1);
/* Enable Error Interrupt             */
LL_SPI_EnableIT_ERR(SPI1);
}
}
else if(a_chDMA == eInterruptEnable){
/* Configure SPI1 DMA transfer interrupts */
/* Enable DMA RX Interrupt */
LL_SPI_EnableDMAReq_RX(SPI1);
/* Enable DMA TX Interrupt */
LL_SPI_EnableDMAReq_TX(SPI1);


 /* DMA1 used for SPI1 Transmission
 * DMA1 used for SPI1 Reception
 */
/* (1) Enable the clock of DMA1 and DMA1 */
LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_DMA1);

 /* (2) Configure NVIC for DMA transfer complete/error interrupts */
NVIC_SetPriority(DMA1_Channel2_IRQn, 0);
NVIC_EnableIRQ(DMA1_Channel2_IRQn);
NVIC_SetPriority(DMA1_Channel3_IRQn, 0);
NVIC_EnableIRQ(DMA1_Channel3_IRQn);

/* (3) Configure the DMA1_Channel2 functional parameters */
LL_DMA_ConfigTransfer(DMA1, LL_DMA_CHANNEL_2,
LL_DMA_DIRECTION_PERIPH_TO_MEMORY | LL_DMA_PRIORITY_HIGH | LL_DMA_MODE_NORMAL |
LL_DMA_PERIPH_NOINCREMENT | LL_DMA_MEMORY_INCREMENT |
LL_DMA_PDATAALIGN_BYTE | LL_DMA_MDATAALIGN_BYTE);
LL_DMA_ConfigAddresses(DMA1, LL_DMA_CHANNEL_2, LL_SPI_DMA_GetRegAddr(SPI1), (uint32_t)Spi1.RxBuf,
 LL_DMA_GetDataTransferDirection(DMA1, LL_DMA_CHANNEL_2));
LL_DMA_SetDataLength(DMA1, LL_DMA_CHANNEL_2, SPIRBUF_SIZE);//Data Size
LL_DMA_SetPeriphRequest(DMA1, LL_DMA_CHANNEL_2, LL_DMA_REQUEST_1);

/* (4) Configure the DMA1_Channel3 functional parameters */
LL_DMA_ConfigTransfer(DMA1, LL_DMA_CHANNEL_3,
LL_DMA_DIRECTION_MEMORY_TO_PERIPH | LL_DMA_PRIORITY_HIGH | LL_DMA_MODE_NORMAL |
LL_DMA_PERIPH_NOINCREMENT | LL_DMA_MEMORY_INCREMENT |
LL_DMA_PDATAALIGN_BYTE | LL_DMA_MDATAALIGN_BYTE);
LL_DMA_ConfigAddresses(DMA1, LL_DMA_CHANNEL_3, (uint32_t)Spi1.TxBuf, LL_SPI_DMA_GetRegAddr(SPI1),
 LL_DMA_GetDataTransferDirection(DMA1, LL_DMA_CHANNEL_3));
LL_DMA_SetDataLength(DMA1, LL_DMA_CHANNEL_3, SPIRBUF_SIZE);//Data Size
LL_DMA_SetPeriphRequest(DMA1, LL_DMA_CHANNEL_3, LL_DMA_REQUEST_1);

/* (5) Enable DMA interrupts complete/error */
LL_DMA_EnableIT_TC(DMA1, LL_DMA_CHANNEL_2);
LL_DMA_EnableIT_TE(DMA1, LL_DMA_CHANNEL_2);
LL_DMA_EnableIT_TC(DMA1, LL_DMA_CHANNEL_3);
LL_DMA_EnableIT_TE(DMA1, LL_DMA_CHANNEL_3);
}

ClearBuf_SPI1();

LL_SPI_Enable(SPI1);

if(a_chDMA == eInterruptEnable){
/* Enable DMA Channels */
LL_DMA_EnableChannel(DMA1, LL_DMA_CHANNEL_2);
LL_DMA_EnableChannel(DMA1, LL_DMA_CHANNEL_3);
}
  }
  else if(a_chSpi == 2)
{
  }
}

/*******************************************************************************
* Function Name : 
* Parameters    : None
* Return        : None
* Description   : 
*******************************************************************************/
uint8_t SPI_FLASH_ReadWite(SPI_TypeDef *SPI_Num, const uint8_t* pTXBuffer, uint8_t* pRXBuffer, uint16_t NumByteToRead)
{
uint16_t w, b;

CLEAR_BIT(SPI_Num->CR2, SPI_RXFIFO_THRESHOLD);
while (NumByteToRead > 1) {
int spiTimeout = 1000;
while (!LL_SPI_IsActiveFlag_TXE(SPI_Num)) {
if ((spiTimeout--) == 0) {
return 0x02;
}
}

if (pTXBuffer) {
w = *((uint16_t *)pTXBuffer);
pTXBuffer += 2;

else {
w = 0xFFFF;
}
*((__IO uint16_t *)&SPI_Num->DR) = w;//LL_SPI_TransmitData16(SPI_Num, w);

spiTimeout = 1000;
while (!LL_SPI_IsActiveFlag_RXNE(SPI_Num)) {
if ((spiTimeout--) == 0) {
return 0x02;
}
}
w = LL_SPI_ReceiveData16(SPI_Num);
if (pRXBuffer) {
*((uint16_t *)pRXBuffer) = w;
pRXBuffer += 2;
}
NumByteToRead -= 2;
}

// set 8-bit transfer
SET_BIT(SPI_Num->CR2, SPI_RXFIFO_THRESHOLD);
if (NumByteToRead) {
int spiTimeout = 1000;
while (!LL_SPI_IsActiveFlag_TXE(SPI_Num)) {
if ((spiTimeout--) == 0) {
return 0x02;
}
}
b = pTXBuffer ? *(pTXBuffer++) : 0xFF;
*((__IO uint8_t *)&SPI_Num->DR) = b;//LL_SPI_TransmitData8(SPI_Num, b);

spiTimeout = 1000;
while (!LL_SPI_IsActiveFlag_RXNE(SPI_Num)) {
if ((spiTimeout--) == 0) {
return 0x02;
}
}

b = (uint8_t)(READ_REG(SPI_Num->DR));// b = LL_SPI_ReceiveData8(SPI_Num);
if (pRXBuffer) {
*(pRXBuffer++) = b;
}
--NumByteToRead;
}

return 0x00;
}

/*******************************************************************************
* Function Name : 
* Parameters    : None
* Return        : None
* Description   : 
*******************************************************************************/
uint8_t SPI_FLASH_SendByte(SPI_TypeDef *SPI_Num, uint8_t byte)
{
uint32_t SPITimeOut = SPI_FLAG_TIMEOUT;
  /* Loop while DR register in not emplty */
  while (!LL_SPI_IsActiveFlag_TXE(SPI_Num)){
if (SPITimeOut-- == 0) return 0x02;
}

  /* Send byte through the SPI1 peripheral */
*((__IO uint8_t *)&SPI_Num->DR) = byte;// LL_SPI_TransmitData8(SPI_Num, byte);

  /* Wait to receive a byte */
SPITimeOut = SPI_FLAG_TIMEOUT;
  while (!LL_SPI_IsActiveFlag_RXNE(SPI_Num)){
if (SPITimeOut-- == 0) return 0x02;
}

  /* Return the byte read from the SPI bus */
return (uint8_t)(READ_REG(SPI_Num->DR));//  return LL_SPI_ReceiveData8(SPI_Num);
}

/*******************************************************************************
* Function Name : 
* Parameters    : None
* Return        : None
* Description   : 
*******************************************************************************/
uint8_t SPI_FLASH_ReadByte(SPI_TypeDef *SPI_Num)
{
  return (SPI_FLASH_SendByte(SPI_Num, DUMMY_BYTE));
}

'초보의 아웅다웅 설계하기 > STM32' 카테고리의 다른 글

ST의 디자인 툴  (0) 2019.06.04
STM32L4 UART/LPUART LL_DRIVER  (0) 2019.05.25
STM32L4 SPI LL_DRIVER  (0) 2019.05.25
Keil 자동완성 기능 끄기  (0) 2019.03.21
PID 제어  (0) 2019.03.02
LSM6DSL, LIS2MDL, LPS22HB  (0) 2019.03.01
Posted by 초보 HW 엔지니어 로망와니

댓글을 달아 주세요

2019.03.21 16:12

한글 자동완성만큼이나 극혐인 Keil 자동완성을 제거하였습니다.

치다가 자동완성때문에 멈춰있는 걸 보면 숨이 탁 막혔는데 이제 그럴 일은 없을 것 같습니다.


Edit -> Configuration -> Text Completion



'초보의 아웅다웅 설계하기 > STM32' 카테고리의 다른 글

STM32L4 UART/LPUART LL_DRIVER  (0) 2019.05.25
STM32L4 SPI LL_DRIVER  (0) 2019.05.25
Keil 자동완성 기능 끄기  (0) 2019.03.21
PID 제어  (0) 2019.03.02
LSM6DSL, LIS2MDL, LPS22HB  (0) 2019.03.01
Base Timer 인터럽트 사용 안하고 설정하기  (1) 2018.12.20
Posted by 초보 HW 엔지니어 로망와니

댓글을 달아 주세요

2019.03.02 11:08

\Drivers\CMSIS\DSP_Lib\Source\ControllerFunctions

안에 arm_pid_init_f32.c 파일을 Merge 시키거나 arm_math 파일만을 묶어서 라이브러리로 만들어 추가해도 됩니다.


실제 사용시에는 다양한 값을 받아서 PID 제어를 하면 될 듯 싶습니다.

조금 더 부드럽게 값을 만져줄 수 있어 몇개의 Factor을 받아 2중 PID 구조를 사용하였습니다. 


#include "arm_math.h"


/* Private typedef -----------------------------------------------------------*/

/* Private define ------------------------------------------------------------*/

/* Private macro ------------------------------------------------------------*/

/* Private variables ---------------------------------------------------------*/

arm_pid_instance_f32 PID_Acc;

arm_pid_instance_f32 PID_Gyro;


/* ACC */

#define PID_PARAM_ACC_P 2         /* Proporcional */

#define PID_PARAM_ACC_I 0.005        /* Integral */

#define PID_PARAM_ACC_D 0.02            /* Derivative */


/* Private function prototypes ------------------------------------------------*/

/* Private functions ---------------------------------------------------------*/

void PID_ACCInit(void);


/*******************************************************************************

* Function Name : 

* Parameters    : None

* Return        : None

* Description   : 

*******************************************************************************/

void PID_Init(void)

{

PID_ACCInit();

}


/*******************************************************************************

* Function Name : 

* Description   : 

* Parameters    : None

* Return        : None

* Description   : 

Gyroscope Sensor

*******************************************************************************/

void PID_ACCInit(void)

{

/* Set PID parameters */

/* Set this for your needs */

PID_Acc.Kp = PID_PARAM_ACC_P;        /* Proporcional */

PID_Acc.Ki = PID_PARAM_ACC_I;        /* Integral */

PID_Acc.Kd = PID_PARAM_ACC_D;        /* Derivative */

/* Initialize PID system, float32_t format */

      arm_pid_init_f32(&PID_Acc, 1);

}


/*******************************************************************************

* Function Name : 

* Parameters    : None

* Return        : None

* Description   : 

*******************************************************************************/

void PID_ACCControl(const float a_fTargetValue, const float a_fCurrentValue)

{

float pid_error = 0;

/* Duty cycle for PWM */

float duty;

pid_error = a_fTargetValue - a_fCurrentValue;

/* Calculate PID here, argument is error */

/* Output data will be returned, we will use it as duty cycle parameter */

duty = 0; duty = arm_pid_f32(&PID_Acc, pid_error);

/* Check overflow, duty cycle in percent */

if (duty >= ACCHIGHLIMIT) {duty = ACCHIGHLIMIT;}

else if (duty <= ACCLOWLIMIT) {duty = ACCLOWLIMIT;}


 PWM(duty);

}

'초보의 아웅다웅 설계하기 > STM32' 카테고리의 다른 글

STM32L4 SPI LL_DRIVER  (0) 2019.05.25
Keil 자동완성 기능 끄기  (0) 2019.03.21
PID 제어  (0) 2019.03.02
LSM6DSL, LIS2MDL, LPS22HB  (0) 2019.03.01
Base Timer 인터럽트 사용 안하고 설정하기  (1) 2018.12.20
STM32F Sleep Mode에서 Uart로 Wakeup하기  (0) 2018.12.06
Posted by 초보 HW 엔지니어 로망와니

댓글을 달아 주세요

2019.03.01 00:52

가속, 자이로, 온도, 압감지, 마그넷 센서

LSM6DSL, LIS2MDL, LPS22HB

소스와 통신하는 부분을 ST에서 제공하는 프로그램에서 발췌했더니 비효율적으로 되어있습니다.

데이터시트를 보고 최적화와 함께 함수들을 만들어 써야합니다. 


void main(void)

{

ACCGyroAxis_TypeDef ACCAxis, GyroAxis;

MagnetAxis_TypeDef MagnetAxis;

float fPress, ftemperature;

float fBatt;

uint16_t Batt_Percent;


LSM6DSL_ACCGyroInit();

LIS2MDL_MagnetInit();

LPS22HB_TempPreInit();


LSM6DSL_ACCGyroEnable();

LIS2MDL_MagnetEnable();

LPS22HB_TempPreEnable();


LSM6DSL_ACCGyroSetting();

LIS2MDL_MagnetSetting();

while(1)

{

MeasurementSensorData(5, &ACCAxis, &GyroAxis, &MagnetAxis, &fPress, &ftemperature, &fBatt, &Batt_Percent);

}

}



/* Private typedef -----------------------------------------------------------*/

/* Private define ------------------------------------------------------------*/

#define LSM6DSL_ACC_SENSITIVITY_FOR_FS_2G   0.061  /**< Sensitivity value for 2 g full scale [mg/LSB] */

#define LSM6DSL_ACC_SENSITIVITY_FOR_FS_4G   0.122  /**< Sensitivity value for 4 g full scale [mg/LSB] */

#define LSM6DSL_ACC_SENSITIVITY_FOR_FS_8G   0.244  /**< Sensitivity value for 8 g full scale [mg/LSB] */

#define LSM6DSL_ACC_SENSITIVITY_FOR_FS_16G  0.488  /**< Sensitivity value for 16 g full scale [mg/LSB] */


#define LSM6DSL_GYRO_SENSITIVITY_FOR_FS_125DPS   04.375  /**< Sensitivity value for 125 dps full scale [mdps/LSB] */

#define LSM6DSL_GYRO_SENSITIVITY_FOR_FS_245DPS   08.750  /**< Sensitivity value for 245 dps full scale [mdps/LSB] */

#define LSM6DSL_GYRO_SENSITIVITY_FOR_FS_500DPS   17.500  /**< Sensitivity value for 500 dps full scale [mdps/LSB] */

#define LSM6DSL_GYRO_SENSITIVITY_FOR_FS_1000DPS  35.000  /**< Sensitivity value for 1000 dps full scale [mdps/LSB] */

#define LSM6DSL_GYRO_SENSITIVITY_FOR_FS_2000DPS  70.000  /**< Sensitivity value for 2000 dps full scale [mdps/LSB] */


#define LSM6DSL_ACC_SENSITIVITY LSM6DSL_ACC_SENSITIVITY_FOR_FS_2G

#define LSM6DSL_GYRO_SENSITIVITY LSM6DSL_GYRO_SENSITIVITY_FOR_FS_2000DPS


typedef enum {

 eModeACC = 0,  

 eModeGyro,  

} eModeACCGyro_TypeDef;


typedef struct {

int32_t ACCGyro_X;

int32_t ACCGyro_Y;

int32_t ACCGyro_Z;

}ACCGyroAxis_TypeDef;


//#define LSM6DSL_RESERVED 0x00

#define LSM6DSL_FUNC_CFG_ACCESS 0x01 //Embedded functions

//#define LSM6DSL_RESERVED 0x02

//#define LSM6DSL_RESERVED 0x03

#define LSM6DSL_SENSOR_SYNC_TIME_FRAME 0x04 //r/w

#define LSM6DSL_SENSOR_SYNC_RES_RATIO 0x05 //r/w

#define LSM6DSL_FIFO_CTRL1 0x06 //r/w

#define LSM6DSL_FIFO_CTRL2 0x07 //r/w

#define LSM6DSL_FIFO_CTRL3 0x08 //r/w

#define LSM6DSL_FIFO_CTRL4 0x09 //r/w

#define LSM6DSL_FIFO_CTRL5 0x0A //r/w

#define LSM6DSL_DRDY_PULSE_CFG_G 0x0B //r/w

//#define LSM6DSL_RESERVED 0x0C

#define LSM6DSL_INT1_CTRL 0x0D //r/w INT1 pin control

#define LSM6DSL_INT2_CTRL 0x0E //r/w INT2 pin control

#define LSM6DSL_WHO_AM_I 0x0F //r Who I am ID

#define LSM6DSL_CTRL1_XL 0x10 //r/w

#define LSM6DSL_CTRL2_G 0x11 //r/w

#define LSM6DSL_CTRL3_C 0x12 //r/w

#define LSM6DSL_CTRL4_C 0x13 //r/w

#define LSM6DSL_CTRL5_C 0x14 //r/w

#define LSM6DSL_CTRL6_C 0x15 //r/w

#define LSM6DSL_CTRL7_G 0x16 //r/w

#define LSM6DSL_CTRL8_XL 0x17 //r/w

#define LSM6DSL_CTRL9_XL 0x18 //r/w

#define LSM6DSL_CTRL10_C 0x19 //r/w

#define LSM6DSL_MASTER_CONFIG 0x1A //r/w

#define LSM6DSL_WAKE_UP_SRC 0x1B //r

#define LSM6DSL_TAP_SRC 0x1C //r  Interrupt registers

#define LSM6DSL_D6D_SRC 0x1D //r  

#define LSM6DSL_STATUS_REG 0x1E //r  

//#define LSM6DSL_RESERVED 0x1F

#define LSM6DSL_OUT_TEMP_L 0x20 //r   Temperature output

#define LSM6DSL_OUT_TEMP_H 0x21 //r   data registers

#define LSM6DSL_OUTX_L_G 0x22 //r   GYRO

#define LSM6DSL_OUTX_H_G 0x23 //r  

#define LSM6DSL_OUTY_L_G 0x24 //r  

#define LSM6DSL_OUTY_H_G 0x25 //r  

#define LSM6DSL_OUTZ_L_G 0x26 //r  

#define LSM6DSL_OUTZ_H_G 0x27 //r  

#define LSM6DSL_OUTX_L_XL 0x28 //r   ACC

#define LSM6DSL_OUTX_H_XL 0x29 //r  

#define LSM6DSL_OUTY_L_XL 0x2A //r  

#define LSM6DSL_OUTY_H_XL 0x2B //r  

#define LSM6DSL_OUTZ_L_XL 0x2C //r  

#define LSM6DSL_OUTZ_H_XL 0x2D //r  

#define LSM6DSL_SENSORHUB1_REG 0x2E //r  

#define LSM6DSL_SENSORHUB2_REG 0x2F //r  

#define LSM6DSL_SENSORHUB3_REG 0x30 //r  

#define LSM6DSL_SENSORHUB4_REG 0x31 //r  

#define LSM6DSL_SENSORHUB5_REG 0x32 //r  

#define LSM6DSL_SENSORHUB6_REG 0x33 //r  

#define LSM6DSL_SENSORHUB7_REG 0x34 //r  

#define LSM6DSL_SENSORHUB8_REG 0x35 //r  

#define LSM6DSL_SENSORHUB9_REG 0x36 //r  

#define LSM6DSL_SENSORHUB10_REG 0x37 //r  

#define LSM6DSL_SENSORHUB11_REG 0x38 //r  

#define LSM6DSL_SENSORHUB12_REG 0x39 //r  

#define LSM6DSL_FIFO_STATUS1 0x3A //r  

#define LSM6DSL_FIFO_STATUS2 0x3B //r  

#define LSM6DSL_FIFO_STATUS3 0x3C //r  

#define LSM6DSL_FIFO_STATUS4 0x3D //r  

#define LSM6DSL_FIFO_DATA_OUT_L 0x3E //r   FIFO data output

#define LSM6DSL_FIFO_DATA_OUT_H 0x3F //r  

#define LSM6DSL_TIMESTAMP0_REG 0x40 //r  

#define LSM6DSL_TIMESTAMP1_REG 0x41 //r  

#define LSM6DSL_TIMESTAMP2_REG 0x42 //r/w  

//#define LSM6DSL_RESERVED 0x43 ~ 0x48

#define LSM6DSL_STEP_TIMESTAMP_L 0x49 //r   Step counter

#define LSM6DSL_STEP_TIMESTAMP_H 0x4A //r   timestamp registers

#define LSM6DSL_STEP_COUNTER_L 0x4B //r   Step counte0xoutput

#define LSM6DSL_STEP_COUNTER_H 0x4C //r   registers

#define LSM6DSL_SENSORHUB13_REG 0x4D //r  

#define LSM6DSL_SENSORHUB14_REG 0x4E //r  

#define LSM6DSL_SENSORHUB15_REG 0x4F //r  

#define LSM6DSL_SENSORHUB16_REG 0x50 //r  

#define LSM6DSL_SENSORHUB17_REG 0x51 //r  

#define LSM6DSL_SENSORHUB18_REG 0x52 //r  

#define LSM6DSL_FUNC_SRC1 0x53 //r  

#define LSM6DSL_FUNC_SRC2 0x54 //r  

#define LSM6DSL_WRIST_TILT_IA 0x55 //r   Interrupt register

//#define LSM6DSL_RESERVED - 56-57 - 

#define LSM6DSL_TAP_CFG 0x58 //r/w  

#define LSM6DSL_TAP_THS_6D 0x59 //r/w  

#define LSM6DSL_INT_DUR2 0x5A //r/w  

#define LSM6DSL_WAKE_UP_THS 0x5B //r/w  

#define LSM6DSL_WAKE_UP_DU0x0x5C //r/w  

#define LSM6DSL_FREE_FALL 0x5D //r/w  

#define LSM6DSL_MD1_CFG 0x5E //r/w  

#define LSM6DSL_MD2_CFG 0x5F //r/w  

#define LSM6DSL_MASTER_CMD_CODE 0x60 //r/w  

#define LSM6DSL_SENS_SYNC_SPI_ERROR_CODE 0x61 //r/w 

//#define LSM6DSL_RESERVED - 62-65 - Reserved

#define LSM6DSL_OUT_MAG_RAW_X_L 0x66 //r  

#define LSM6DSL_OUT_MAG_RAW_X_H 0x67 //r  

#define LSM6DSL_OUT_MAG_RAW_Y_L 0x68 //r  

#define LSM6DSL_OUT_MAG_RAW_Y_H 0x69 //r  

#define LSM6DSL_OUT_MAG_RAW_Z_L 0x6A //r  

#define LSM6DSL_OUT_MAG_RAW_Z_H 0x6B //r  

//#define LSM6DSL_RESERVED - 6C-72 - 

#define LSM6DSL_X_OFS_US0x0x73 //r/w  

#define LSM6DSL_Y_OFS_US0x0x74 //r/w  

#define LSM6DSL_Z_OFS_US0x0x75 //r/w  

//#define LSM6DSL_RESERVED - 76-7F -



/* Private macro ------------------------------------------------------------*/

/* Private variables ---------------------------------------------------------*/

/* Private function prototypes ------------------------------------------------*/

/* Private functions ---------------------------------------------------------*/

extern void UART1_printf(const char *fmt,...);

ACCGyroAxis_TypeDef gstACCAxis;

ACCGyroAxis_TypeDef gstGyroAxis;



/*******************************************************************************

* Function Name : 

* Parameters    : None

* Return        : None

* Description   : 

*******************************************************************************/

void LSM6DSL_ACCGyroInit(void)

{

uint8_t Data[10];


Data[0] = 0x0C;

SPI2_1Wire_Write(CS_LSM6DSL, LSM6DSL_CTRL3_C, Data, 1);

Data[0] = 0x00;

SPI2_1Wire_Read(CS_LSM6DSL, LSM6DSL_WHO_AM_I, Data, 1);

Data[0] = 0x6A;

SPI2_1Wire_Read(CS_LSM6DSL, LSM6DSL_CTRL3_C, Data, 1);

Data[0] = 0x0C;

SPI2_1Wire_Write(CS_LSM6DSL, LSM6DSL_CTRL3_C, Data, 1);

SPI2_1Wire_Read(CS_LSM6DSL, LSM6DSL_CTRL3_C, Data, 1);

Data[0] = 0x4C;

SPI2_1Wire_Write(CS_LSM6DSL, LSM6DSL_CTRL3_C, Data, 1);

SPI2_1Wire_Read(CS_LSM6DSL, LSM6DSL_FIFO_CTRL5, Data, 1);

Data[0] = 0x00;

SPI2_1Wire_Write(CS_LSM6DSL, LSM6DSL_FIFO_CTRL5, Data, 1);

SPI2_1Wire_Read(CS_LSM6DSL, LSM6DSL_CTRL1_XL, Data, 1);

Data[0] = 0x00;

SPI2_1Wire_Write(CS_LSM6DSL, LSM6DSL_CTRL1_XL, Data, 1);

SPI2_1Wire_Read(CS_LSM6DSL, LSM6DSL_CTRL1_XL, Data, 1);

Data[0] = 0x00;

SPI2_1Wire_Write(CS_LSM6DSL, LSM6DSL_CTRL1_XL, Data, 1);

SPI2_1Wire_Read(CS_LSM6DSL, LSM6DSL_CTRL4_C, Data, 1);

Data[0] = 0x04;

SPI2_1Wire_Write(CS_LSM6DSL,LSM6DSL_CTRL4_C, Data, 1);

Data[0] = 0x00;

SPI2_1Wire_Read(CS_LSM6DSL, LSM6DSL_WHO_AM_I, Data, 1);

Data[0] = 0x6A;

SPI2_1Wire_Read(CS_LSM6DSL, LSM6DSL_CTRL3_C, Data, 1);

Data[0] = 0x4C;

SPI2_1Wire_Write(CS_LSM6DSL, LSM6DSL_CTRL3_C, Data, 1);

SPI2_1Wire_Read(CS_LSM6DSL, LSM6DSL_CTRL3_C, Data, 1);

Data[0] = 0x4C;

SPI2_1Wire_Write(CS_LSM6DSL, LSM6DSL_CTRL3_C, Data, 1);

SPI2_1Wire_Read(CS_LSM6DSL, LSM6DSL_FIFO_CTRL5, Data, 1);

Data[0] = 0x00;

SPI2_1Wire_Write(CS_LSM6DSL, LSM6DSL_FIFO_CTRL5, Data, 1);

SPI2_1Wire_Read(CS_LSM6DSL, LSM6DSL_CTRL2_G, Data, 1);

Data[0] = 0x0C;

SPI2_1Wire_Write(CS_LSM6DSL, LSM6DSL_CTRL2_G, Data, 1);

SPI2_1Wire_Read(CS_LSM6DSL, LSM6DSL_CTRL2_G, Data, 1);

Data[0] = 0x0C;

SPI2_1Wire_Write(CS_LSM6DSL, LSM6DSL_CTRL2_G, Data, 1);

SPI2_1Wire_Read(CS_LSM6DSL, LSM6DSL_CTRL4_C, Data, 1);

Data[0] = 0x04;

SPI2_1Wire_Write(CS_LSM6DSL, LSM6DSL_CTRL4_C, Data, 1);

}


/*******************************************************************************

* Function Name : 

* Parameters    : None

* Return        : None

* Description   : 

<- \ ACC + / ACC-

Side

Right - Left +

*******************************************************************************/

void LSM6DSL_ACCGyroEnable(void)

{

uint8_t Data[10], ACCGyroLoop;

Data[0] = 0x01;

SPI2_1Wire_Read(CS_LSM6DSL, LSM6DSL_CTRL1_XL, Data, 1);

Data[0] = 0x40;

SPI2_1Wire_Write(CS_LSM6DSL, LSM6DSL_CTRL1_XL, Data, 1);

Data[0] = 0x0A;

SPI2_1Wire_Read(CS_LSM6DSL, LSM6DSL_CTRL2_G, Data, 1);

Data[0] = 0x4C;

SPI2_1Wire_Write(CS_LSM6DSL, LSM6DSL_CTRL2_G, Data, 1);

delay_ms(100);

ACCGyroAxis_TypeDef ACCAxis, GyroAxis;

LSM6DSL_ACCGyroGet(&gstACCAxis, &gstGyroAxis);

for(ACCGyroLoop = 0; ACCGyroLoop < 10; ACCGyroLoop++){

LSM6DSL_ACCGyroGet(&ACCAxis, &GyroAxis);

gstACCAxis.ACCGyro_X = (gstACCAxis.ACCGyro_X + ACCAxis.ACCGyro_X)/2;

gstACCAxis.ACCGyro_Y = (gstACCAxis.ACCGyro_Y + ACCAxis.ACCGyro_Y)/2;

gstACCAxis.ACCGyro_Z = (gstACCAxis.ACCGyro_Z + ACCAxis.ACCGyro_Z)/2;

gstGyroAxis.ACCGyro_X = (gstGyroAxis.ACCGyro_X + GyroAxis.ACCGyro_X)/2;

gstGyroAxis.ACCGyro_Y = (gstGyroAxis.ACCGyro_Y + GyroAxis.ACCGyro_Y)/2;

gstGyroAxis.ACCGyro_Z = (gstGyroAxis.ACCGyro_Z + GyroAxis.ACCGyro_Z)/2;

delay_ms(1);

}

}


/*******************************************************************************

* Function Name : 

* Parameters    : None

* Return        : None

* Description   : 

*******************************************************************************/

void LSM6DSL_ACCGyroSetting(void)

{

uint8_t Data[10];


//ODR 6.6kHz   

Data[0] = 0x0A;

SPI2_1Wire_Read(CS_LSM6DSL, 0x10, Data, 1);

Data[0] = 0xA0;

SPI2_1Wire_Write(CS_LSM6DSL, 0x10, Data, 1);

//FS 4g

Data[0] = 0xA0;

SPI2_1Wire_Read(CS_LSM6DSL, 0x10, Data, 1);

Data[0] = 0xA8;

SPI2_1Wire_Write(CS_LSM6DSL, 0x10, Data, 1);

//ODR/2 low pass filtered sent to composite filter

Data[0] = 0xA8;

SPI2_1Wire_Read(CS_LSM6DSL, 0x17, Data, 1);

Data[0] &= ~0x80;//LSM6DSL_ACC_GYRO_IN_COMP_MASK;

  Data[0] |= 0x00;//LSM6DSL_ACC_GYRO_IN_ODR_DIV_2;

SPI2_1Wire_Write(CS_LSM6DSL, 0x17, Data, 1);

//Enable LPF2 filter in composite filter block

Data[0] = 0x60;

SPI2_1Wire_Read(CS_LSM6DSL, 0x17, Data, 1);

Data[0] &= ~0x80;//LSM6DSL_ACC_GYRO_LPF2_XL_MASK;

  Data[0] |= 0x80;//LSM6DSL_ACC_GYRO_LPF2_XL_ENABLE;

SPI2_1Wire_Write(CS_LSM6DSL, 0x17, Data, 1);

//Low pass filter @ ODR/400

Data[0] = 0xE0;

SPI2_1Wire_Read(CS_LSM6DSL, 0x17, Data, 1);

Data[0] &= ~0x60;//LSM6DSL_ACC_GYRO_HPCF_XL_MASK;

  Data[0] |= 0x60;//LSM6DSL_ACC_GYRO_HPCF_XL_DIV400;

SPI2_1Wire_Write(CS_LSM6DSL, 0x17, Data, 1);

//ACC Read

Data[0] = 0x00;

SPI2_1Wire_Read(CS_LSM6DSL, 0x10, Data, 1);

//Set LSB to 0 >> Analog filter 1500Hz

Data[0] &= 0xFE;

SPI2_1Wire_Write(CS_LSM6DSL, 0x10, Data, 1);

// Initialize settings for 6-axis MEMS Gyroscope 

// FS 2000dps */

// ODR 416Hz */

// LPF1 FTYPE set to 10b 

Data[0] = 0xA8;

SPI2_1Wire_Read(CS_LSM6DSL, 0x15, Data, 1);

Data[0] &= ~0x03;//LSM6DSL_ACC_GYRO_FTYPE_MASK   

  Data[0] |= 0x01;//LSM6DSL_ACC_GYRO_LP_G_NARROW 

SPI2_1Wire_Write(CS_LSM6DSL, 0x15, Data, 1);

//Gyroscope settings: full scale 2000dps, ODR 416Hz

Data[0] = 0x6C;

SPI2_1Wire_Write(CS_LSM6DSL, 0x11, Data, 1);

}

/*******************************************************************************

* Function Name : 

* Parameters    : None

* Return        : None

* Description   : 

*******************************************************************************/

void LSM6DSL_ACCGyro(uint8_t *pRawdata, ACCGyroAxis_TypeDef *ACCGyroAxis, eModeACCGyro_TypeDef chMode)

{

short int ACCGyroTemp;

if(chMode == eModeACC){

ACCGyroTemp = ((((uint16_t)pRawdata[1]) << 8) + (uint16_t)pRawdata[0]);

ACCGyroAxis->ACCGyro_X = (ACCGyroTemp * LSM6DSL_ACC_SENSITIVITY);

ACCGyroTemp = ((((uint16_t)pRawdata[3]) << 8) + (uint16_t)pRawdata[2]);

ACCGyroAxis->ACCGyro_Y = (ACCGyroTemp * LSM6DSL_ACC_SENSITIVITY);

ACCGyroTemp = ((((uint16_t)pRawdata[5]) << 8) + (uint16_t)pRawdata[4]);

ACCGyroAxis->ACCGyro_Z = (ACCGyroTemp * LSM6DSL_ACC_SENSITIVITY);

}

else if(chMode == eModeGyro){

ACCGyroTemp = ((((uint16_t)pRawdata[1]) << 8) + (uint16_t)pRawdata[0]);

ACCGyroAxis->ACCGyro_X = (ACCGyroTemp * LSM6DSL_GYRO_SENSITIVITY);

ACCGyroTemp = ((((uint16_t)pRawdata[3]) << 8) + (uint16_t)pRawdata[2]);

ACCGyroAxis->ACCGyro_Y = (ACCGyroTemp * LSM6DSL_GYRO_SENSITIVITY);

ACCGyroTemp = ((((uint16_t)pRawdata[5]) << 8) + (uint16_t)pRawdata[4]);

ACCGyroAxis->ACCGyro_Z = (ACCGyroTemp * LSM6DSL_GYRO_SENSITIVITY);

}

}


/*******************************************************************************

* Function Name : 

* Parameters    : None

* Return        : None

* Description   : 

*******************************************************************************/

void LSM6DSL_RawData(uint8_t *pAddr, uint8_t *pRawData, uint8_t chLen)

{

uint8_t SpiLoop;

for(SpiLoop = 0; SpiLoop < chLen; SpiLoop++){

// UART1_printf("%02X, %02X, %02X \r\n", CS_LSM6DSL, pAddr[SpiLoop], pRawData[SpiLoop]);

SPI2_1Wire_Read(CS_LSM6DSL, pAddr[SpiLoop], &pRawData[SpiLoop], 1 );

}

}


/*******************************************************************************

* Function Name : 

* Parameters    : None

* Return        : None

* Description   : 

*******************************************************************************/

void LSM6DSL_ACCGyroGet(ACCGyroAxis_TypeDef *ACCAxis, ACCGyroAxis_TypeDef *GyroAxis)

{

const uint8_t Data_ACCGyro[15] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A, 0xFE};

uint8_t Addr_ACCGyro[15] = \

{LSM6DSL_OUTX_L_XL, LSM6DSL_OUTX_H_XL, LSM6DSL_OUTY_L_XL, LSM6DSL_OUTY_H_XL, LSM6DSL_OUTZ_L_XL, LSM6DSL_OUTZ_H_XL\

, LSM6DSL_CTRL1_XL,\

LSM6DSL_OUTX_L_G, LSM6DSL_OUTX_H_G, LSM6DSL_OUTY_L_G, LSM6DSL_OUTY_H_G, LSM6DSL_OUTZ_L_G, LSM6DSL_OUTZ_H_G\

, LSM6DSL_CTRL2_G, LSM6DSL_CTRL2_G};

uint8_t Data[15] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A, 0xFE};

uint8_t pData[6];


memcpy(Data, Data_ACCGyro, 15);

LSM6DSL_RawData(Addr_ACCGyro, Data, 15);//0~5, 7~12

memcpy(pData, Data, 6);

LSM6DSL_ACCGyro(pData, ACCAxis, eModeACC);

memcpy(pData, Data+7, 6);

LSM6DSL_ACCGyro(pData, GyroAxis, eModeGyro);

}


/* Private typedef -----------------------------------------------------------*/

/* Private define ------------------------------------------------------------*/

typedef struct {

int32_t Mag_X;

int32_t Mag_Y;

int32_t Mag_Z;

}MagnetAxis_TypeDef;


//#define LIS2MDL_Reserved 00 - 44 Reserved

#define LIS2MDL_OFFSET_X_REG_L 0x45 //r/w  Hard-iron registers

#define LIS2MDL_OFFSET_X_REG_H 0x46 //r/w 

#define LIS2MDL_OFFSET_Y_REG_L 0x47 //r/w 

#define LIS2MDL_OFFSET_Y_REG_H 0x48 //r/w 

#define LIS2MDL_OFFSET_Z_REG_L 0x49 //r/w 

#define LIS2MDL_OFFSET_Z_REG_H 0x4A //r/w 

//#define LIS2MDL_RESERVED 4B-4C Reserved

#define LIS2MDL_WHO_AM_I 0x4F //r 

//#define LIS2MDL_RESERVED 50-5F Reserved

#define LIS2MDL_CFG_REG_A 0x60 //r/w  Configuration

#define LIS2MDL_CFG_REG_B 0x61 //r/w 

#define LIS2MDL_CFG_REG_C 0x62 //r/w 

#define LIS2MDL_INT_CRTL_REG 0x63 //r/w  configuration registers

#define LIS2MDL_INT_SOURCE_REG 0x64 //r

#define LIS2MDL_INT_THS_L_REG 0x65 //r/w 

#define LIS2MDL_INT_THS_H_REG 0x66 //r/w 

#define LIS2MDL_STATUS_REG 0x67 //r

#define LIS2MDL_OUTX_L_REG 0x68 //r  Output registers

#define LIS2MDL_OUTX_H_REG 0x69 //r 

#define LIS2MDL_OUTY_L_REG 0x6A //r 

#define LIS2MDL_OUTY_H_REG 0x6B //r 

#define LIS2MDL_OUTZ_L_REG 0x6C //r 

#define LIS2MDL_OUTZ_H_REG 0x6D //r 

#define LIS2MDL_TEMP_OUT_L_REG 0x6E //r  Temperature sensor

#define LIS2MDL_TEMP_OUT_H_REG 0x6F //r 


/* Private macro ------------------------------------------------------------*/

/* Private variables ---------------------------------------------------------*/

/* Private function prototypes ------------------------------------------------*/

/* Private functions ---------------------------------------------------------*/

extern void UART1_printf(const char *fmt,...);

MagnetAxis_TypeDef gStMagnetAxis;


/*******************************************************************************

* Function Name : 

* Parameters    : None

* Return        : None

* Description   : 

*******************************************************************************/

void LIS2MDL_MagnetInit(void)

{

uint8_t Data[10];


Data[0] = 0x00;

SPI2_1Wire_Read(CS_LIS2MDL, LIS2MDL_WHO_AM_I, Data, 1);

Data[0] = 0x40;

SPI2_1Wire_Read(CS_LIS2MDL, LIS2MDL_CFG_REG_A, Data, 1);//reboot memory content

Data[0] = 0x0F;

SPI2_1Wire_Write(CS_LIS2MDL, LIS2MDL_CFG_REG_A, Data, 1);//Output data rate configuration - 50Hz

SPI2_1Wire_Read(CS_LIS2MDL, LIS2MDL_CFG_REG_C, Data, 1);

Data[0] = 0x10;

SPI2_1Wire_Write(CS_LIS2MDL, LIS2MDL_CFG_REG_C, Data, 1);// reading of incorrect data is avoided when the user reads asynchronously

SPI2_1Wire_Read(CS_LIS2MDL, LIS2MDL_CFG_REG_A, Data, 1);

Data[0] = 0x0F;

SPI2_1Wire_Write(CS_LIS2MDL, LIS2MDL_CFG_REG_A, Data, 1);

SPI2_1Wire_Read(CS_LIS2MDL, LIS2MDL_CFG_REG_C, Data, 1);

Data[0] = 0x10;

SPI2_1Wire_Write(CS_LIS2MDL, LIS2MDL_CFG_REG_C, Data, 1);

}


/*******************************************************************************

* Function Name : 

* Parameters    : None

* Return        : None

* Description   : 

1. Write CFG_REG_A = 80h // Enable temperature compensation

//Mag = 10 Hz (high-resolution and continuous mode)

2. Write CFG_REG_C = 01h // Mag data-ready interrupt enable

*******************************************************************************/

void LIS2MDL_MagnetEnable(void)

{

uint8_t Data[10];


Data[0] = 0x0A;

SPI2_1Wire_Read(CS_LIS2MDL, LIS2MDL_CFG_REG_A, Data, 1);

Data[0] = 0x0C;

SPI2_1Wire_Write(CS_LIS2MDL, LIS2MDL_CFG_REG_A, Data, 1);//100Hz

}



/*******************************************************************************

* Function Name : 

* Parameters    : None

* Return        : None

* Description   : 

Initialize settings for Magnetometer settings 

(By default after reset is in in idle mode) 

*******************************************************************************/

void LIS2MDL_MagnetSetting(void)

{

uint8_t Data[10];


Data[0] = 0x8C;

SPI2_1Wire_Write(CS_LIS2MDL, LIS2MDL_CFG_REG_A, Data, 1);

Data[0] = 0x02;

SPI2_1Wire_Write(CS_LIS2MDL, LIS2MDL_CFG_REG_B, Data, 1);

}

/*******************************************************************************

* Function Name : 

* Parameters    : None

* Return        : None

* Description   : 

*******************************************************************************/

void LIS2MDL_Magnet(uint8_t *pRawdata, MagnetAxis_TypeDef *MagnetAxis, float fSensitivity)

{

short int MagnetTemp;

MagnetTemp = (((uint16_t)pRawdata[1]) << 8) + (uint16_t)pRawdata[0];

MagnetAxis->Mag_X = (MagnetTemp * fSensitivity);

MagnetTemp = (((uint16_t)pRawdata[3]) << 8) + (uint16_t)pRawdata[2];

MagnetAxis->Mag_Y  = (MagnetTemp * fSensitivity);

MagnetTemp = (((uint16_t)pRawdata[5]) << 8) + (uint16_t)pRawdata[4];

MagnetAxis->Mag_Z  = (MagnetTemp * fSensitivity);

}


/*******************************************************************************

* Function Name : 

* Parameters    : None

* Return        : None

* Description   : 

*******************************************************************************/

void LIS2MDL_RawData(uint8_t *pAddr, uint8_t *pRawData, uint8_t chLen)

{

uint8_t SpiLoop;

for(SpiLoop = 0; SpiLoop < chLen; SpiLoop++){

// UART1_printf("%02X, %02X, %02X \r\n", CS_LIS2MDL, pAddr[SpiLoop], pRawData[SpiLoop]);

SPI2_1Wire_Read(CS_LIS2MDL, pAddr[SpiLoop], &pRawData[SpiLoop], 1 );

}

}


/*******************************************************************************

* Function Name : 

* Parameters    : None

* Return        : None

* Description   : 

*******************************************************************************/

void LIS2MDL_MagnetGet(MagnetAxis_TypeDef *MagnetAxis)

{

uint8_t Addr_Magnet[6] = {0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D};

uint8_t Data[6] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00};


int16_t *pRawData;

float Sensitivity = 1.5f;

LIS2MDL_RawData(Addr_Magnet, Data, 6);

LIS2MDL_Magnet(Data, MagnetAxis, Sensitivity);

}


/* Private typedef -----------------------------------------------------------*/

/* Private define ------------------------------------------------------------*/

//#define LPS22HB_Reserved 0x00 - 0A - Reserved

#define LPS22HB_INTERRUPT_CFG 0x0B //r/w Interrupt register

#define LPS22HB_THS_P_L 0x0C //r/w threshold registers

#define LPS22HB_THS_P_H 0x0D //r/w

//#define LPS22HB_Reserved 0E - Reserved

#define LPS22HB_WHO_AM_I 0x0F //r Who am I

#define LPS22HB_CTRL_REG1 0x10 //r/w

#define LPS22HB_CTRL_REG2 0x11 //r/w Control registers

#define LPS22HB_CTRL_REG3 0x12 //r/w

//#define LPS22HB_Reserved 13 - Reserved

#define LPS22HB_FIFO_CTRL 0x14 //r/w FIFO configuration register

#define LPS22HB_REF_P_XL 0x15 //r/w

#define LPS22HB_REF_P_L 0x16 //r/w Reference pressure registers

#define LPS22HB_REF_P_H 0x17 //r/w

#define LPS22HB_RPDS_L 0x18 //r/w offset registers

#define LPS22HB_RPDS_H 0x19 //r/w

#define LPS22HB_RES_CONF 0x1A //r/w Resolution register

//#define LPS22HB_Reserved 1B - 24 - Reserved

#define LPS22HB_INT_SOURCE 0x25 //r Interrupt register

#define LPS22HB_FIFO_STATUS 0x26 //r FIFO status register

#define LPS22HB_STATUS 0x27 //r Status register

#define LPS22HB_PRESS_OUT_XL 0x28 //r

#define LPS22HB_PRESS_OUT_L 0x29 //r Pressure output registers

#define LPS22HB_PRESS_OUT_H 0x2A //r

#define LPS22HB_TEMP_OUT_L 0x2B //r Temperature output registers

#define LPS22HB_TEMP_OUT_H 0x2C //r

//#define LPS22HB_Reserved 2D - 32 - Reserved

#define LPS22HB_LPFP_RES 0x33 //r Filte0xreset register


/* Private macro ------------------------------------------------------------*/

/* Private variables ---------------------------------------------------------*/

/* Private function prototypes ------------------------------------------------*/

/* Private functions ---------------------------------------------------------*/


/*******************************************************************************

* Function Name : 

* Parameters    : None

* Return        : None

* Description   : 

*******************************************************************************/

void LPS22HB_TempPreInit(void)

{

uint8_t Data[10];


Data[0] = 0x01;

SPI2_1Wire_Write(CS_LPS22HB, LPS22HB_CTRL_REG1, Data, 1);

SPI2_1Wire_Read(CS_LPS22HB, LPS22HB_CTRL_REG2, Data, 1);

Data[0] = 0xFC;

SPI2_1Wire_Write(CS_LPS22HB, LPS22HB_CTRL_REG2, Data, 1);

Data[0] = 0x01;

SPI2_1Wire_Write(CS_LPS22HB, LPS22HB_CTRL_REG1, Data, 1);

SPI2_1Wire_Read(CS_LPS22HB, LPS22HB_CTRL_REG1, Data, 1);

Data[0] = 0x01;

SPI2_1Wire_Write(CS_LPS22HB, LPS22HB_CTRL_REG1, Data, 1);

Data[0] = 0x00;

SPI2_1Wire_Read(CS_LPS22HB, LPS22HB_WHO_AM_I, Data, 1);


Data[0] = 0xB1;

SPI2_1Wire_Read(CS_LPS22HB, LPS22HB_RES_CONF, Data, 1);


Data[0] = 0x01;

SPI2_1Wire_Write(CS_LPS22HB, LPS22HB_RES_CONF, Data, 1);

SPI2_1Wire_Read(CS_LPS22HB, LPS22HB_CTRL_REG1, Data, 1);

Data[0] = 0x01;

SPI2_1Wire_Write(CS_LPS22HB, LPS22HB_CTRL_REG1, Data, 1);

SPI2_1Wire_Read(CS_LPS22HB, LPS22HB_CTRL_REG1, Data, 1);

Data[0] = 0x01;

SPI2_1Wire_Write(CS_LPS22HB, LPS22HB_CTRL_REG1, Data, 1);

SPI2_1Wire_Read(CS_LPS22HB, LPS22HB_CTRL_REG1, Data, 1);

Data[0] = 0x01;

SPI2_1Wire_Write(CS_LPS22HB, LPS22HB_CTRL_REG1, Data, 1);

SPI2_1Wire_Read(CS_LPS22HB, LPS22HB_CTRL_REG1, Data, 1);


Data[0] = 0x03;

SPI2_1Wire_Write(CS_LPS22HB, LPS22HB_CTRL_REG1, Data, 1);

SPI2_1Wire_Read(CS_LPS22HB, LPS22HB_CTRL_REG2, Data, 1);


Data[0] = 0x00;

SPI2_1Wire_Write(CS_LPS22HB, LPS22HB_CTRL_REG2, Data, 1);

SPI2_1Wire_Read(CS_LPS22HB, LPS22HB_CTRL_REG1, Data, 1);


Data[0] = 0x03;

SPI2_1Wire_Write(CS_LPS22HB, LPS22HB_CTRL_REG1, Data, 1);

SPI2_1Wire_Read(CS_LPS22HB, LPS22HB_CTRL_REG2, Data, 1);


Data[0] = 0xF8;

SPI2_1Wire_Write(CS_LPS22HB, LPS22HB_CTRL_REG2, Data, 1);

}


/*******************************************************************************

* Function Name : 

* Parameters    : None

* Return        : None

* Description   : 

*******************************************************************************/

void LPS22HB_TempPreEnable(void)

{

uint8_t Data[10];

Data[0] = 0x0A;

SPI2_1Wire_Read(CS_LPS22HB, LPS22HB_CTRL_REG1, Data, 1);

Data[0] = 0x33;

SPI2_1Wire_Write(CS_LPS22HB, LPS22HB_CTRL_REG1, Data, 1);

SPI2_1Wire_Read(CS_LPS22HB, LPS22HB_CTRL_REG1, Data, 1);


Data[0] = 0x0A;

SPI2_1Wire_Read(CS_LPS22HB, LPS22HB_CTRL_REG1, Data, 1);


Data[0] = 0x33;

SPI2_1Wire_Write(CS_LPS22HB, LPS22HB_CTRL_REG1, Data, 1);

SPI2_1Wire_Read(CS_LPS22HB, LPS22HB_CTRL_REG1, Data, 1);

}


/*******************************************************************************

* Function Name : 

* Parameters    : None

* Return        : None

* Description   : 

*******************************************************************************/

void LPS22HB_Press(uint8_t *pRawdata, float *fPress)

{

int32_t RawPresse, Pout;

  uint32_t Temp = 0;

  uint8_t PressLoop;


  for(PressLoop = 0; PressLoop < 3; PressLoop++){

    Temp |= (((uint32_t)pRawdata[PressLoop]) << (8 * PressLoop));

}


  /* convert the 2's complement 24 bit to 2's complement 32 bit */

  if(Temp & 0x00800000){

    Temp |= 0xFF000000;

}


  RawPresse = ((int32_t)Temp);

Pout = (RawPresse * 100) / 4096;

*fPress = ( float )Pout / 100.0f;

}


/*******************************************************************************

* Function Name : 

* Parameters    : None

* Return        : None

* Description   : 

*******************************************************************************/

void LPS22HB_Temperature(uint8_t *pRawdata, float *fTemperature)

{

short int TemperatureTemp = 0, Tout = 0;

TemperatureTemp = (((uint16_t)pRawdata[1]) << 8) + (uint16_t)pRawdata[0];

Tout = (TemperatureTemp * 10) / 100;

*fTemperature = (float)Tout / 10.0f;

}


/*******************************************************************************

* Function Name : 

* Parameters    : None

* Return        : None

* Description   : 

*******************************************************************************/

void LPS22HB_RawData(uint8_t *pAddr, uint8_t *pRawData, uint8_t chLen)

{

uint8_t SpiLoop;

for(SpiLoop = 0; SpiLoop < chLen; SpiLoop++){

// UART1_printf("%02X, %02X, %02X \r\n", CS_LPS22HB, pAddr[SpiLoop], pRawData[SpiLoop]);

SPI2_1Wire_Read(CS_LPS22HB, pAddr[SpiLoop], &pRawData[SpiLoop], 1 );

}

}


/*******************************************************************************

* Function Name : 

* Parameters    : None

* Return        : None

* Description   : 

*******************************************************************************/

void LPS22HB_TempPressGet(float *fPress, float *ftemperature)

{

uint8_t Addr_Temperature[2] = {0x2B, 0x2C};

uint8_t Addr_Pressure[3] = {0x28, 0x29, 0x2A};

  uint8_t data[3] = {0x4F, 0xFF, 0x00};

LPS22HB_RawData(Addr_Temperature, data, 2);

LPS22HB_Temperature(data, ftemperature);


LPS22HB_RawData(Addr_Pressure, data, 3);

LPS22HB_Press(data, fPress);

}


/*******************************************************************************

* Function Name : 

* Parameters    : None

* Return        : 

* Description   : 

*******************************************************************************/

void MeasurementSensorData(const uint8_t ConvertType,ACCGyroAxis_TypeDef *pACCAxis, ACCGyroAxis_TypeDef *pGyroAxis, MagnetAxis_TypeDef *pMagnetAxis, float *pfPress, float *pftemperature, float *pfBatt, uint16_t *pBatt_Percent)

{

int32_t Tmp;


ACCGyroAxis_TypeDef ACCAxis, GyroAxis;

MagnetAxis_TypeDef MagnetAxis;

float fPress, ftemperature;


/* Measurement */

LSM6DSL_ACCGyroGet(&ACCAxis, &GyroAxis);

LIS2MDL_MagnetGet(&MagnetAxis);

LPS22HB_TempPressGet(pfPress, pftemperature);

*pfBatt = Calculation_VBAT(uhADCxConvertedValue[0], 0);

*pBatt_Percent = Calculation_VBAT_Percent(*pfBatt, MINVOLTAGE, MAXVOLTAGE, TARGETPERCENT);

pMagnetAxis->Mag_X = (int32_t) MagnetAxis.Mag_X;

pMagnetAxis->Mag_Y = (int32_t) MagnetAxis.Mag_Y;

pMagnetAxis->Mag_Z = (int32_t) MagnetAxis.Mag_Z;


if(ConvertType == 1){

Tmp = pACCAxis->ACCGyro_X;

pACCAxis->ACCGyro_X = pACCAxis->ACCGyro_Y;

pACCAxis->ACCGyro_Y = -Tmp;


Tmp = pGyroAxis->ACCGyro_X;

pGyroAxis->ACCGyro_X = pGyroAxis->ACCGyro_Y;

pGyroAxis->ACCGyro_Y = -Tmp;


Tmp = pMagnetAxis->Mag_X;

pMagnetAxis->Mag_X = pMagnetAxis->Mag_Y;

pMagnetAxis->Mag_Y = -Tmp;

}

else if (ConvertType == 2){

}

else if (ConvertType == 3){

pACCAxis->ACCGyro_X = -ACCAxis.ACCGyro_Y;

pACCAxis->ACCGyro_Y = ACCAxis.ACCGyro_X;

pACCAxis->ACCGyro_Z = ACCAxis.ACCGyro_Z;


pGyroAxis->ACCGyro_X = -GyroAxis.ACCGyro_Y; 

pGyroAxis->ACCGyro_Y = GyroAxis.ACCGyro_X;

pGyroAxis->ACCGyro_Z = GyroAxis.ACCGyro_Z;


pMagnetAxis->Mag_X = -MagnetAxis.Mag_Y;

pMagnetAxis->Mag_Y = MagnetAxis.Mag_X;

}

else if (ConvertType == 4){

pACCAxis->ACCGyro_X = -ACCAxis.ACCGyro_X; 

pACCAxis->ACCGyro_Y = -ACCAxis.ACCGyro_Y;


pGyroAxis->ACCGyro_X = -GyroAxis.ACCGyro_X;            

pGyroAxis->ACCGyro_Y = -GyroAxis.ACCGyro_Y;


pMagnetAxis->Mag_X = -MagnetAxis.Mag_X;

pMagnetAxis->Mag_Y = -MagnetAxis.Mag_Y;

}

else if (ConvertType == 5){

pACCAxis->ACCGyro_X = ACCAxis.ACCGyro_X; 

pACCAxis->ACCGyro_Y = ACCAxis.ACCGyro_Y;

pACCAxis->ACCGyro_Z = ACCAxis.ACCGyro_Z;


pGyroAxis->ACCGyro_X = GyroAxis.ACCGyro_X;            

pGyroAxis->ACCGyro_Y = GyroAxis.ACCGyro_Y;

pGyroAxis->ACCGyro_Z = GyroAxis.ACCGyro_Z;

}

}




'초보의 아웅다웅 설계하기 > STM32' 카테고리의 다른 글

Keil 자동완성 기능 끄기  (0) 2019.03.21
PID 제어  (0) 2019.03.02
LSM6DSL, LIS2MDL, LPS22HB  (0) 2019.03.01
Base Timer 인터럽트 사용 안하고 설정하기  (1) 2018.12.20
STM32F Sleep Mode에서 Uart로 Wakeup하기  (0) 2018.12.06
SoftUart Only TX  (2) 2018.10.22
Posted by 초보 HW 엔지니어 로망와니

댓글을 달아 주세요

2018.12.20 22:02

Base Timer 인터럽트 사용 안하고 설정하기 


uint32_t timers = 0;


TIM_HandleTypeDef    TimHandle;


void main(void)

{

  HAL_Init();

  /* Configure the system clock to 48 MHz */

  SystemClock_Config();


  /* Compute the prescaler value to have TIMx counter clock equal to 10000 Hz */

  uwPrescalerValue = (uint32_t)(SystemCoreClock / 1000000) - 1;//48000000


UART1_printf("SystemCoreClock : %d, uwPrescalerValue %d\r\n", SystemCoreClock, uwPrescalerValue);  


  /* Set TIMx instance */

  TimHandle.Instance = TIMx;


  /* Initialize TIMx peripheral as follows:

       + Period = 10000 - 1

       + Prescaler = (SystemCoreClock/10000) - 1

       + ClockDivision = 0

       + Counter direction = Up

  */

  TimHandle.Init.Period            = 2000000; // about 1000000 = 1s, 100000 = 0.1s 10000 = 0.01s, 1000 = 0.001s, 100 = 0.0001s, 10 = 0.00001s, 1 = 0.000001s  

  TimHandle.Init.Prescaler         = uwPrescalerValue;

  TimHandle.Init.ClockDivision     = 0;

  TimHandle.Init.CounterMode       = TIM_COUNTERMODE_UP;

  TimHandle.Init.RepetitionCounter = 0;

  if (HAL_TIM_Base_Init(&TimHandle) != HAL_OK)

  {

    /* Initialization Error */

    Error_Handler();

  }


__HAL_TIM_SetCounter(&TimHandle, 0);

HAL_TIM_Base_Start(&TimHandle);

uint32_t beforetime=0;

while(1){

if(__HAL_TIM_GetCounter(&TimHandle) >= 1000000){

__HAL_TIM_SetCounter(&TimHandle, 0);

UART1_printf("%d, ", timers);

timers++;

}

}

}


'초보의 아웅다웅 설계하기 > STM32' 카테고리의 다른 글

PID 제어  (0) 2019.03.02
LSM6DSL, LIS2MDL, LPS22HB  (0) 2019.03.01
Base Timer 인터럽트 사용 안하고 설정하기  (1) 2018.12.20
STM32F Sleep Mode에서 Uart로 Wakeup하기  (0) 2018.12.06
SoftUart Only TX  (2) 2018.10.22
24LC1025 데이터 Read, Write  (0) 2018.10.16
Posted by 초보 HW 엔지니어 로망와니

댓글을 달아 주세요

  1. uocraft 2019.01.15 16:55 신고  댓글주소  수정/삭제  댓글쓰기

    간단하면서 유용하네요!

2018.12.06 00:21

STM32F091 기준으로 하였습니다.

다른 시리즈와는 라이브러리가 달라 변경이 필요합니다.


main.c 파일에서 

int main(void)

{

  HAL_Init();


  /* Configure the system clock to 48 MHz */

  SystemClock_Config();

  /* Configure LED2 */

  BSP_LED_Init(LED2);


  /*##-1- Configure the UART peripheral ######################################*/

  /* Put the USART peripheral in the Asynchronous mode (UART Mode) */

  /* UART configured as follows:

      - Word Length = 8 Bits

      - Stop Bit = One Stop bit

      - Parity = None

      - BaudRate = 9600 baud

      - Hardware flow control disabled (RTS and CTS signals) */

  UartHandle.Instance        = USARTx;


  UartHandle.Init.BaudRate   = 9600;

  UartHandle.Init.WordLength = UART_WORDLENGTH_8B;

  UartHandle.Init.StopBits   = UART_STOPBITS_1;

  UartHandle.Init.Parity     = UART_PARITY_NONE;

  UartHandle.Init.HwFlowCtl  = UART_HWCONTROL_NONE;

  UartHandle.Init.Mode       = UART_MODE_TX_RX;

  UartHandle.AdvancedInit.AdvFeatureInit = UART_ADVFEATURE_NO_INIT; 

  if(HAL_UART_DeInit(&UartHandle) != HAL_OK)

  {

    Error_Handler();

  }  

  if(HAL_UART_Init(&UartHandle) != HAL_OK)

  {

    Error_Handler();

  }

__HAL_UART_ENABLE_IT(&UartHandle, UART_IT_RXNE);


  

UART1_printf("Start\r\n");

  /* Configure User push-button in Interrupt mode */

  BSP_PB_Init(BUTTON_USER, BUTTON_MODE_EXTI);

  

  /* Wait for User push-button press before starting the Communication.

     In the meantime, LED2 is blinking */

  while(UserButtonStatus == 0)

  {

      /* Toggle LED2*/

      BSP_LED_Toggle(LED2); 

      HAL_Delay(100);

  }

  

  BSP_LED_Off(LED2); 

  

UART1_printf("HAL_PWR_EnterSTANDBYMode");

//HAL_PWR_DisableSEVOnPend();

//HAL_PWR_DisableSleepOnExit();

//HAL_PWR_DeInit();

HAL_SuspendTick();

HAL_PWR_EnterSLEEPMode(PWR_MAINREGULATOR_ON, PWR_SLEEPENTRY_WFI);//PWR_MAINREGULATOR_ON, PWR_LOWPOWERREGULATOR_ON

HAL_ResumeTick();

  

  /* Turn on LED2 if test passes then enter infinite loop */

  BSP_LED_On(LED2); 

  /* Infinite loop */

  while (1)

  {

UART1_printf("HAL_PWR_Wakeup");

HAL_Delay(1000);

  }

}


/**

  * @brief  System Clock Configuration

  *         The system Clock is configured as follow : 

  *            System Clock source            = PLL (HSI48)

  *            SYSCLK(Hz)                     = 48000000

  *            HCLK(Hz)                       = 48000000

  *            AHB Prescaler                  = 1

  *            APB1 Prescaler                 = 1

  *            HSI Frequency(Hz)              = 48000000

  *            PREDIV                         = 2

  *            PLLMUL                         = 2

  *            Flash Latency(WS)              = 1

  * @param  None

  * @retval None

  */

void SystemClock_Config(void)

{

  RCC_ClkInitTypeDef RCC_ClkInitStruct;

  RCC_OscInitTypeDef RCC_OscInitStruct;

  

  /* Select HSI48 Oscillator as PLL source */

  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI48;

  RCC_OscInitStruct.HSI48State = RCC_HSI48_ON;

  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;

  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI48;

  RCC_OscInitStruct.PLL.PREDIV = RCC_PREDIV_DIV2;

  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL2;

  if (HAL_RCC_OscConfig(&RCC_OscInitStruct)!= HAL_OK)

  {

    /* Initialization Error */

    while(1); 

  }


  /* Select PLL as system clock source and configure the HCLK and PCLK1 clocks dividers */

  RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1);

  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;

  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;

  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1)!= HAL_OK)

  {

    /* Initialization Error */

    while(1); 

  }

}


stm32f0xx_it.c 파일에서

extern void UART1_PutChar(char data);

void USARTx_IRQHandler(void)

{

uint8_t ch;

// HAL_UART_IRQHandler(&UartHandle); // HAL 드라이버가 제공하는 IRQ 핸들러

if ((__HAL_UART_GET_FLAG(&UartHandle, UART_FLAG_RXNE) != RESET) && (__HAL_UART_GET_IT_SOURCE(&UartHandle, UART_IT_RXNE) != RESET)) { 

ch = 0x41;

UART1_PutChar(ch);

}

__HAL_UART_CLEAR_IT(&UartHandle, UART_CLEAR_PEF);

__HAL_UART_CLEAR_IT(&UartHandle, UART_FLAG_RXNE);

/* Disable the UART Parity Error Interrupt and RXNE interrupt*/

CLEAR_BIT(UartHandle.Instance->CR1, (USART_CR1_RXNEIE | USART_CR1_PEIE));

/* Disable the UART Error Interrupt: (Frame error, noise error, overrun error) */

CLEAR_BIT(UartHandle.Instance->CR3, USART_CR3_EIE);

}


stm32f0xx_hal_msp.c 파일에서

void HAL_UART_MspInit(UART_HandleTypeDef *huart)

{  

  GPIO_InitTypeDef  GPIO_InitStruct;

  

  /*##-1- Enable peripherals and GPIO Clocks #################################*/

  /* Enable GPIO TX/RX clock */

  USARTx_TX_GPIO_CLK_ENABLE();

  USARTx_RX_GPIO_CLK_ENABLE();



  /* Enable USARTx clock */

  USARTx_CLK_ENABLE(); 

  

  /*##-2- Configure peripheral GPIO ##########################################*/  

  /* UART TX GPIO pin configuration  */

  GPIO_InitStruct.Pin       = USARTx_TX_PIN;

  GPIO_InitStruct.Mode      = GPIO_MODE_AF_PP;

  GPIO_InitStruct.Pull      = GPIO_PULLUP;

  GPIO_InitStruct.Speed     = GPIO_SPEED_FREQ_HIGH;

  GPIO_InitStruct.Alternate = USARTx_TX_AF;


  HAL_GPIO_Init(USARTx_TX_GPIO_PORT, &GPIO_InitStruct);


  /* UART RX GPIO pin configuration  */

  GPIO_InitStruct.Pin = USARTx_RX_PIN;

  GPIO_InitStruct.Alternate = USARTx_RX_AF;


  HAL_GPIO_Init(USARTx_RX_GPIO_PORT, &GPIO_InitStruct);

    

  /*##-3- Configure the NVIC for UART ########################################*/

  /* NVIC for USART */

  HAL_NVIC_SetPriority(USARTx_IRQn, 0, 0);

  HAL_NVIC_EnableIRQ(USARTx_IRQn);

}


/**

  * @brief UART MSP De-Initialization 

  *        This function frees the hardware resources used in this example:

  *          - Disable the Peripheral's clock

  *          - Revert GPIO and NVIC configuration to their default state

  * @param huart: UART handle pointer

  * @retval None

  */

void HAL_UART_MspDeInit(UART_HandleTypeDef *huart)

{

  /*##-1- Reset peripherals ##################################################*/

  USARTx_FORCE_RESET();

  USARTx_RELEASE_RESET();


  /*##-2- Disable peripherals and GPIO Clocks #################################*/

  /* Configure UART Tx as alternate function  */

  HAL_GPIO_DeInit(USARTx_TX_GPIO_PORT, USARTx_TX_PIN);

  /* Configure UART Rx as alternate function  */

  HAL_GPIO_DeInit(USARTx_RX_GPIO_PORT, USARTx_RX_PIN);

  

  /*##-3- Disable the NVIC for UART ##########################################*/

  HAL_NVIC_DisableIRQ(USARTx_IRQn);

}



Posted by 초보 HW 엔지니어 로망와니

댓글을 달아 주세요

2018.10.22 13:07

참고 사이트 : 

https://github.com/blalor/avr-softuart


위 사이트에 나와있는 소스코드를 STM32F103에서 동작하도록 변경

9600bps에 맞췄습니다만 본인이 사용하는 클럭 설정이나 다른 코어라면 코어의 처리 속도등을 고려해서 Timer의 발생 시간을 조절해주어야 합니다. 

계산해보면 1/9600 = 0.00010416... 이므로 오차율 감안하고 104us정도 나오도록 오실로스코프로 계산하면서 맞춰주면 될 것 같습니다.

softuart.c



##include <stdarg.h>

#include <stdio.h>


#define SU_TRUE    1

#define SU_FALSE   0



// 1 Startbit, 8 Databits, 1 Stopbit = 10 Bits/Frame

#define TX_NUM_OF_BITS (10)

volatile static unsigned char  flag_tx_busy;

volatile static unsigned char  timer_tx_ctr;

volatile static unsigned char  bits_left_in_tx;

volatile static unsigned short internal_tx_buffer; /* ! mt: was type uchar - this was wrong */


#define UARTTXPORT GPIOA

#define UARTTXPIN GPIO_Pin_9


#define set_tx_pin_high()      GPIO_SetBits(UARTTXPORT, UARTTXPIN)

#define set_tx_pin_low()       GPIO_ResetBits(UARTTXPORT, UARTTXPIN)



extern void TIM2_IRQHandler(void);

void TIM2_IRQHandler(void) 

{

  if (TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)

  {

    TIM_ClearITPendingBit(TIM2, TIM_IT_Update);

Tim2_IRQ();

  }

}


void Tim2_IRQ(void)

{

unsigned char tmp;

// Transmitter Section

if ( flag_tx_busy == SU_TRUE ) {

tmp = timer_tx_ctr;

if ( --tmp == 0 ) { // if ( --timer_tx_ctr <= 0 )

if ( internal_tx_buffer & 0x01 ) {

set_tx_pin_high();

}

else {

set_tx_pin_low();

}

internal_tx_buffer >>= 1;

tmp = 3; // timer_tx_ctr = 3;

if ( --bits_left_in_tx == 0 ) {

flag_tx_busy = SU_FALSE;

}

}

timer_tx_ctr = tmp;

}

}


void gpio_init(void)

{

GPIO_InitTypeDef GPIO_InitStruct;


/* Enable the GPIO_LED clock */

RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);


set_tx_pin_high(); /* mt: set to high to avoid garbage on init */


/* Configure Led pin as output */

GPIO_InitStruct.GPIO_Pin = UARTTXPIN;

GPIO_InitStruct.GPIO_Mode = GPIO_Mode_Out_PP;

GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;

GPIO_Init(UARTTXPORT, &GPIO_InitStruct);

flag_tx_busy  = SU_FALSE;

}


void timer_init(void)

{

TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;

NVIC_InitTypeDef NVIC_InitStructure;

RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);


/* Time base configuration */

TIM_TimeBaseStructure.TIM_Period = 70 - 1;  // 

TIM_TimeBaseStructure.TIM_Prescaler = 35; // Timer/Count2 Clock = 36Mhz / (35 + 1) = 1Mhz = 1 usec

TIM_TimeBaseStructure.TIM_ClockDivision = 0;

TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; // Ä«¿îÅ͸ðµåµ¿ÀÛ

TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);


/* TIM2 counter enable */

TIM_Cmd(TIM2, ENABLE);


/* TIM IT enable */

TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);


/* Enable the TIM2 gloabal Interrupt */

NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;

NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;

NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;

NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;

NVIC_Init(&NVIC_InitStructure);

}



void softuart_init( void )

{

gpio_init();

/* 9600bps Setting */

timer_init();

}


unsigned char softuart_transmit_busy( void ) 

{

return ( flag_tx_busy == SU_TRUE ) ? 1 : 0;

}


void softuart_putchar( const char ch )

{

while ( flag_tx_busy == SU_TRUE ) {

; // wait for transmitter ready

  // add watchdog-reset here if needed;

}


// invoke_UART_transmit

timer_tx_ctr       = 3;

bits_left_in_tx    = TX_NUM_OF_BITS;

internal_tx_buffer = ( ch << 1 ) | 0x200;

flag_tx_busy       = SU_TRUE;

}

void softuart_puts( const char *s )

{

while ( *s ) {

softuart_putchar( *s++ );

}

}


void softuart_puts_P(char *string)

{

while(*string != '\0') softuart_putchar(*(string++));

}


void softuart_print(const char *fmt,...)

{

char string[256];

va_list ap;


va_start(ap,fmt);

vsprintf(string,fmt,ap);

va_end(ap);


softuart_puts_P(string);

}



void main(void)

{

softuart_init();

softuart_print("\r\nSoftuart Demo-Application Start \r\n");

}



Posted by 초보 HW 엔지니어 로망와니

댓글을 달아 주세요

  1. uocraft 2018.11.10 15:59 신고  댓글주소  수정/삭제  댓글쓰기

    울온 관련 포스팅 좀...

2018.10.16 09:05


int main(void)

{

 I2C_PortInit();


/* 초기 쓰레기값 읽어주기 */

     AT24LCXX_Init();

for(uint32_t i=0; i<260; i++){

tAT24CXX(i);

}

}





/* Includes ------------------------------------------------------------------*/

#include "stm32f10x.h"

#include "usr_softI2C.h"

#include "usr_uart.h"

#include "string.h"


/* Defines -------------------------------------------------------------------*/

#define I2C_PORT GPIOB

#define I2C_SCL GPIO_Pin_6          

#define I2C_SDA GPIO_Pin_7         


#define AT24CXX_BLOCKA_ADDR   0xA0//1010 0000

#define AT24CXX_BLOCKB_ADDR   0xA8//1010 1000


/*******************************************************************************

* Function Name : 

* Description   : 

* Parameters    : None

* Return        : None

*******************************************************************************/

void I2C_PortInit(void)

{

    /* I2C1 Periph clock enable */

    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);

    RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);


    GPIO_InitTypeDef  GPIO_InitStructure;


    /* Configure I2C1 pins: SCL and SDA */

    GPIO_InitStructure.GPIO_Pin =  I2C_SCL | I2C_SDA;

    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;

    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_OD;

    GPIO_Init(I2C_PORT, &GPIO_InitStructure);

}


/*******************************************************************************

* Function Name : 

* Parameters    : 

* Return        : none

* Description   : 

*******************************************************************************/

void I2C_WRITE(unsigned char dat)

{

u8 bit_cnt, tmp;

u8 bit_value;


for(bit_cnt=0; bit_cnt<8; bit_cnt++)

{

tmp = (dat << bit_cnt) & 0x80;

bit_value = (tmp >> 7) & 0x01;


if(bit_value == 1)

GPIO_SetBits(I2C_PORT,I2C_SDA);

else

GPIO_ResetBits(I2C_PORT,I2C_SDA);

delay_us(5);

GPIO_SetBits(I2C_PORT,I2C_SCL);

delay_us(5);

GPIO_ResetBits(I2C_PORT,I2C_SCL);

delay_us(5);

}

}


/*******************************************************************************

* Function Name : 

* Parameters    : 

* Return        : none

* Description   : 

*******************************************************************************/

void I2C_START(void)

{

GPIO_SetBits(I2C_PORT,I2C_SCL);//SCL=1;

delay_us(5);

GPIO_SetBits(I2C_PORT,I2C_SDA);//SDA=1;

delay_us(5);

GPIO_ResetBits(I2C_PORT,I2C_SDA);//SDA=0;

delay_us(5);

GPIO_ResetBits(I2C_PORT,I2C_SCL);//SCL=0;

delay_us(5);

}


/*******************************************************************************

* Function Name : 

* Parameters    : 

* Return        : none

* Description   : 

*******************************************************************************/

void I2C_STOP(void)

{

GPIO_ResetBits(I2C_PORT,I2C_SDA);

delay_us(5);

GPIO_SetBits(I2C_PORT,I2C_SCL);

delay_us(5);

GPIO_SetBits(I2C_PORT,I2C_SDA);

delay_us(7);

}


/*******************************************************************************

* Function Name : 

* Parameters    : 

* Return        : none

* Description   : 

*******************************************************************************/

void I2C_SEND_ACK(u8 bit_value)

{

if(bit_value == 1)

GPIO_SetBits(I2C_PORT,I2C_SDA);

else

GPIO_ResetBits(I2C_PORT,I2C_SDA);


delay_us(5);

GPIO_SetBits(I2C_PORT,I2C_SCL);

delay_us(5);

GPIO_ResetBits(I2C_PORT,I2C_SCL);

delay_us(5);

GPIO_SetBits(I2C_PORT,I2C_SDA);

delay_us(5);

}


/*******************************************************************************

* Function Name : 

* Parameters    : 

* Return        : none

* Description   : 

*******************************************************************************/

uint8_t I2C_READ(void)

{

uint8_t i_byte, n;


GPIO_SetBits(I2C_PORT,I2C_SDA);

delay_us(5);


GPIO_InitTypeDef  GPIO_InitStructure;


/* Configure I2C1 pins: SCL and SDA */

GPIO_InitStructure.GPIO_Pin =  I2C_SDA;

GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;

GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;

GPIO_Init(I2C_PORT, &GPIO_InitStructure);


for(n=0; n<8; n++)

{

GPIO_SetBits(I2C_PORT,I2C_SCL);

delay_us(5);


if (GPIO_ReadInputDataBit(I2C_PORT,I2C_SDA)){

i_byte = (i_byte << 1) | 0x01; // msbit first

}

else{

i_byte = i_byte << 1;

}

GPIO_ResetBits(I2C_PORT,I2C_SCL);

delay_us(5);

}


/* Configure I2C1 pins: SCL and SDA */

GPIO_InitStructure.GPIO_Pin =  I2C_SDA;

GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;

GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_OD;

GPIO_Init(I2C_PORT, &GPIO_InitStructure);


return(i_byte);

}


/*******************************************************************************

* Function Name : 

* Description   : 

* Parameters    : None

* Return        : None

*******************************************************************************/

void AT24CXX_Write(uint8_t Address, uint16_t addr, uint8_t* pBuffer,  uint16_t NumByteToWrite)

{

uint16_t unNum = 0;

for(uint8_t i=0; i <= NumByteToWrite/128; i++)

{

I2C_START();

I2C_WRITE(Address);

I2C_SEND_ACK(0);

I2C_WRITE((addr >> 8) & 0xff); // high byte of memory address

I2C_SEND_ACK(0);

I2C_WRITE(addr & 0xff); // low byte of mem address

I2C_SEND_ACK(0);

if(i < NumByteToWrite/128){

unNum = 128;

}

else{

unNum = NumByteToWrite%128;

}

/* While there is data to be written */

while(unNum--){

/* Send the current byte */

I2C_WRITE(*pBuffer);

/* Point to the next byte to be written */

pBuffer++;

I2C_SEND_ACK(0);

}

I2C_STOP();

addr += 128;


delay_ms(20);

}

}


/*******************************************************************************

* Function Name : 

* Description   : 

* Parameters    : None

* Return        : None

*******************************************************************************/

void AT24CXX_Read(uint8_t Address, uint16_t addr, uint8_t* pBuffer,  uint16_t NumByteToWrite)

{

I2C_START();

I2C_WRITE(Address);

I2C_SEND_ACK(0);

I2C_WRITE((addr >> 8) & 0xff);

I2C_SEND_ACK(0);

I2C_WRITE(addr & 0xff);

I2C_SEND_ACK(0);


I2C_START();

I2C_WRITE(Address | (1 << 0));

I2C_SEND_ACK(0);

 

while(NumByteToWrite--)

{

*pBuffer = I2C_READ();

pBuffer++;

if(NumByteToWrite){

I2C_SEND_ACK(0);

}

else{

I2C_SEND_ACK(1);

}

}

I2C_STOP();

}



/*******************************************************************************

* Function Name : 

* Description   : 

* Parameters    : None

* Return        : None

*******************************************************************************/

void AT24LCXX_1ByteWrite(uint8_t dev_adr, uint16_t mem_adr, uint8_t a_chDat)

{

I2C_START();

I2C_WRITE(AT24CXX_BLOCKA_ADDR | (dev_adr << 1));

I2C_SEND_ACK(0);

I2C_WRITE((mem_adr >> 8) & 0xff); // high byte of memory address

I2C_SEND_ACK(0);

I2C_WRITE(mem_adr & 0xff); // low byte of mem address

I2C_SEND_ACK(0);

I2C_WRITE(a_chDat); // and finally the data

I2C_SEND_ACK(0);

I2C_STOP();


delay_ms(25); // allow for the programming of the eeprom

}


/*******************************************************************************

* Function Name : 

* Description   : 

* Parameters    : None

* Return        : None

*******************************************************************************/

uint8_t AT24LCXX_1ByteRead(uint8_t dev_adr, uint16_t mem_adr)

{

uint8_t Dat;


I2C_START();

I2C_WRITE(AT24CXX_BLOCKA_ADDR | (dev_adr << 1));

I2C_SEND_ACK(0);

I2C_WRITE((mem_adr >> 8) & 0xff);

I2C_SEND_ACK(0);

I2C_WRITE(mem_adr & 0xff);

I2C_SEND_ACK(0);


I2C_START(); // no intermediate stop

I2C_WRITE(0xa1 | (dev_adr << 1)); // read operation

I2C_SEND_ACK(0);

Dat = I2C_READ();

I2C_SEND_ACK(1);

I2C_STOP();


return Dat;

}


/*******************************************************************************

* Function Name : 

* Description   : 

* Parameters    : None

* Return        : None

*******************************************************************************/

uint8_t AT24LCXX_Init(void)

{

uint8_t ch;

/* Dummy */

ch = AT24LCXX_1ByteRead(0x00, 0x00);

return ch;

}


/*******************************************************************************

* Function Name : 

* Description   : 

* Parameters    : None

* Return        : None

*******************************************************************************/

void tAT24CXX(uint32_t addr)

{

uint32_t mem_adr;

uint8_t dat[512], ch;

uint16_t n;

mem_adr = addr *512;

UART2_printf("addr %d, mem_adr %d \r\n", addr, mem_adr);

memset(dat, 0, sizeof(dat));

if(mem_adr < 0xFFFF){

AT24CXX_Read(AT24CXX_BLOCKA_ADDR, mem_adr, dat, 512);

}

else{

AT24CXX_Read(AT24CXX_BLOCKB_ADDR, mem_adr, dat, 512);

}

printData("dat b", dat, 512);


if(dat[0] != 0x32)

{

dat[0] = 0x32;

dat[1] = (addr >> 8) & 0xff;

dat[2] = (addr & 0xff);

UART2_printf("dat[1] %d, dat[2] %d \r\n", dat[1], dat[2]);

for(n=3; n<512; n++){

dat[n] = (uint8_t)(n%255);

}

if(mem_adr < 0xFFFF){

AT24CXX_Write(AT24CXX_BLOCKA_ADDR, mem_adr, dat, 512);

}

else{

AT24CXX_Write(AT24CXX_BLOCKB_ADDR, mem_adr, dat, 512);

}

printData("dat f", dat, 512);

}

delay_ms(1000);

}



/*******************************************************************************

* Function Name : 

* Description   : 

* Parameters    : None

* Return        : None

*******************************************************************************/

void tAT24CXX_1Byte(void)

{

long mem_adr;

uint8_t dat[512];

uint16_t n;


AT24LCXX_Init();

mem_adr=0x0000;

UART2_printf("dat b\r\n");

for(n=0; n<512; n++)

{

dat[n] = AT24LCXX_1ByteRead(0x00, mem_adr);

UART2_printf("%x", dat[n]);

++mem_adr;

}

UART2_printf("\r\n");

if(dat[0] != 0x31)

{

UART2_printf("dat f\r\n");

mem_adr=0x0000;

dat[0] = 0x31;

AT24LCXX_1ByteWrite(0x00, mem_adr, dat[0]);

mem_adr=0x0001;

for(n=1; n<512; n++)

{

dat[n] = (uint8_t)(n%255);

UART2_printf("%x", dat[n]);

AT24LCXX_1ByteWrite(0x00, mem_adr, dat[n]);

++mem_adr;

}

UART2_printf("\r\n");

UART2_printf("Write\r\n");

}


delay_ms(1500);

}



Posted by 초보 HW 엔지니어 로망와니

댓글을 달아 주세요

2018.09.01 21:04

OLED QG-2864KSWLG01를 구해서 프로그램을 넣었습니다.

웹에 도는 소스코드와 데이터시트로 구현을 하여도 동작을 하지 않았습니다.

명령어를 넣을 때 데이터 시트와 웹에서는 0x80을 실제로는 0x00을 넣어야했습니다.

그리고 ACK 자리에도 데이터 시트와 웹에서는 1을 실제로는 0을 넣어야 했습니다.

아래 샘플코드입니다.

I2C가 패리패럴로 구현되지 않고 IO로 구현되어있습니다.

RES는 회로상에서 NPN TR로 ON/OFF 해서 High와 Low가 역으로 되어있습니다.



#define OLED_ADDRESS 0x78


#define I2C_PORT GPIOB

#define I2C_SCL GPIO_Pin_6         

#define I2C_SDA GPIO_Pin_7   

#define LCDRSTPORT GPIOE

#define LCDRSTPIN GPIO_Pin_2

#define LCDENPORT GPIOB

#define LCDENPIN GPIO_Pin_5



/*******************************************************************************

* Function Name : 

* Parameters    : 

* Return        : none

* Description   : 

*******************************************************************************/

static void OLED_RES(FunctionalState NewState)

{

  if (NewState == DISABLE){

    GPIO_SetBits(LCDRSTPORT, LCDRSTPIN);

  }

  else{

    GPIO_ResetBits(LCDRSTPORT, LCDRSTPIN);

  }

}


/*******************************************************************************

* Function Name : 

* Parameters    : 

* Return        : none

* Description   : 

*******************************************************************************/

void OLED_EN(FunctionalState NewState)

{

  if (NewState == DISABLE){

    GPIO_ResetBits(LCDENPORT, LCDENPIN);

  }

  else{

    GPIO_SetBits(LCDENPORT, LCDENPIN);

  }

}


/*******************************************************************************

* Function Name : 

* Parameters    : 

* Return        : none

* Description   : 

*******************************************************************************/

void OLED_SDA(FunctionalState NewState)

{

  if (NewState == DISABLE){

    GPIO_ResetBits(I2C_PORT, I2C_SDA);

  }

  else{

    GPIO_SetBits(I2C_PORT, I2C_SDA);

  }

}


/*******************************************************************************

* Function Name : 

* Parameters    : 

* Return        : none

* Description   : 

*******************************************************************************/

void OLED_SCL(FunctionalState NewState)

{

  if (NewState == DISABLE){

    GPIO_ResetBits(I2C_PORT, I2C_SCL);

  }

  else{

    GPIO_SetBits(I2C_PORT, I2C_SCL);

  }

}


/*******************************************************************************

* Function Name : 

* Parameters    : 

* Return        : none

* Description   : 

*******************************************************************************/

void OLED_Config(void)

GPIO_InitTypeDef GPIO_InitStructure;

RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);

RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOE, ENABLE);


OLED_RES(DISABLE);

OLED_EN(DISABLE);

GPIO_SetBits(I2C_PORT,I2C_SDA);

GPIO_SetBits(I2C_PORT,I2C_SCL);

/* LCD SDA/SCL */

GPIO_InitStructure.GPIO_Pin = I2C_SCL | I2C_SDA;

GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;

GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;

GPIO_Init(I2C_PORT, &GPIO_InitStructure);  

/* LCD EN */

GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5;

GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;

GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;

GPIO_Init(GPIOB, &GPIO_InitStructure);  


/* LCD RST */

GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;

GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;

GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;

GPIO_Init(GPIOE, &GPIO_InitStructure);  

}


/*******************************************************************************

* Function Name : 

* Parameters    : 

* Return        : none

* Description   : 

*******************************************************************************/

void I2C_WRITE(unsigned char dat)

{

u8 bit_cnt, tmp;

u8 bit_value;


for(bit_cnt=0; bit_cnt<8; bit_cnt++)

{

tmp = (dat << bit_cnt) & 0x80;

bit_value = (tmp >> 7) & 0x01;


if(bit_value == 1)

GPIO_SetBits(I2C_PORT,I2C_SDA);

else

GPIO_ResetBits(I2C_PORT,I2C_SDA);

delay_us(3);

GPIO_SetBits(I2C_PORT,I2C_SCL);

delay_us(3);

GPIO_ResetBits(I2C_PORT,I2C_SCL);

delay_us(3);

}

}


/*******************************************************************************

* Function Name : 

* Parameters    : 

* Return        : none

* Description   : 

*******************************************************************************/

void I2C_Start(void)

{

GPIO_SetBits(I2C_PORT,I2C_SCL);//SCL=1;

delay_us(3);

GPIO_SetBits(I2C_PORT,I2C_SDA);//SDA=1;

delay_us(3);

GPIO_ResetBits(I2C_PORT,I2C_SDA);//SDA=0;

delay_us(3);

GPIO_ResetBits(I2C_PORT,I2C_SCL);//SCL=0;

delay_us(3);

}


/*******************************************************************************

* Function Name : 

* Parameters    : 

* Return        : none

* Description   : 

*******************************************************************************/

void I2C_Stop(void)

{

GPIO_ResetBits(I2C_PORT,I2C_SDA);

delay_us(3);

GPIO_SetBits(I2C_PORT,I2C_SCL);

delay_us(3);

GPIO_SetBits(I2C_PORT,I2C_SDA);

delay_us(5);

}


/*******************************************************************************

* Function Name : 

* Parameters    : 

* Return        : none

* Description   : 

*******************************************************************************/

void I2C_Ack(u8 bit_value)

{

if(bit_value == 1)

GPIO_SetBits(I2C_PORT,I2C_SDA);

else

GPIO_ResetBits(I2C_PORT,I2C_SDA);


delay_us(3);

GPIO_SetBits(I2C_PORT,I2C_SCL);

delay_us(3);

GPIO_ResetBits(I2C_PORT,I2C_SCL);

delay_us(3);

GPIO_SetBits(I2C_PORT,I2C_SDA);

delay_us(3);

}


/*******************************************************************************

* Function Name : 

* Parameters    : 

* Return        : none

* Description   : 

*******************************************************************************/

void write_i(unsigned char ins)

{

I2C_Start();

I2C_WRITE(OLED_ADDRESS);

I2C_Ack(0);

I2C_WRITE(0x00);

I2C_Ack(0);

I2C_WRITE(ins);

I2C_Ack(0);

I2C_Stop();

}


/*******************************************************************************

* Function Name : 

* Parameters    : 

* Return        : none

* Description   : 

*******************************************************************************/

void write_d(unsigned char dat)

{

I2C_Start();

I2C_WRITE(OLED_ADDRESS);

I2C_Ack(0);

I2C_WRITE(0x40);

I2C_Ack(0);

I2C_WRITE(dat);

I2C_Ack(0);

I2C_Stop();

}          


/*******************************************************************************

* Function Name : 

* Parameters    : 

* Return        : none

* Description   : 

*******************************************************************************/

void OLED_Init_InternalPump(void)

{

OLED_EN(ENABLE);

delay_us(1000);


OLED_RES(ENABLE);////RES=1;  

delay_us(1000);

OLED_RES(DISABLE);//RES=0;   

delay_us(1000);      

OLED_RES(ENABLE);////RES=1;

delay_us(1000);


write_i(0xAE);    /*display off*/       


write_i(0x02);    /*set lower column address*/       

write_i(0x10);    /*set higher column address*/


write_i(0x40);    /*set display start line*/


write_i(0xB0);    /*set page address*/


write_i(0x81);    /*contract control*/

write_i(0x80);    /*128*/


write_i(0xA1);    /*set segment remap*/


write_i(0xA6);    /*normal / reverse*/


write_i(0xA8);    /*multiplex ratio*/

write_i(0x3F);    /*duty = 1/64*/


write_i(0xad);    /*set charge pump enable*/

write_i(0x8b);     /*    0x8B    ??VCC   */


write_i(0x33);    /*0X30---0X33  set VPP   9V */


write_i(0xC8);    /*Com scan direction*/


write_i(0xD3);    /*set display offset*/

write_i(0x00);   /*   0x20  */


write_i(0xD5);    /*set osc division*/

write_i(0x80);    


write_i(0xD9);    /*set pre-charge period*/

write_i(0x1f);    /*0x22*/


write_i(0xDA);    /*set COM pins*/

write_i(0x12);


write_i(0xdb);    /*set vcomh*/

write_i(0x30);           


Fill_RAM(0x00); // Clear Screen

write_i(0xAF);    /*display ON*/    

}


/*******************************************************************************

* Function Name : 

* Parameters    : 

* Return        : none

* Description   : 

*******************************************************************************/

void main(void)

{

OLED_Config();

OLED_Init_InternalPump();


}

Posted by 초보 HW 엔지니어 로망와니

댓글을 달아 주세요

2018.08.17 15:16

Keil 컴파일러를 사용하여 다운로드할 때 발생하는 에러 처리 방법


다운로드할 칩의 메모리 사이즈가 맞지 않을 경우 발생


Load "STM32F401xx\\STM32F401xx.axf" 

No Algorithm found for: 0806E000H - 0806FFFFH

No Algorithm found for: 08070000H - 0807FFF3H

Partial Erase Done (areas with no algorithms skipped!)

No Algorithm found for: 0806E000H - 0806FFFFH

No Algorithm found for: 08070000H - 0807FFF3H

Partial Programming Done (areas with no algorithms skipped!)

Partial Verify OK (areas with no algorithms skipped!)

Application running ...




Posted by 초보 HW 엔지니어 로망와니

댓글을 달아 주세요

2018.08.17 13:06


Keil에서 고정 위치에 바이너리 라이팅하기 

const unsigned char FixedROM[65520UL + 1] __attribute__((at(0x08010000))) = {0x00, };



IAR에서 고정위치에 바이너리 라이팅하기
#pragma location = 0x08010000
__root const unsigned char FixedROM[65520UL + 1] = {0x00, };


0x08010000는 위치하고 싶은 주소 



Posted by 초보 HW 엔지니어 로망와니

댓글을 달아 주세요

2018.08.16 14:56


Posted by 초보 HW 엔지니어 로망와니

댓글을 달아 주세요

2018.07.27 23:42

LCD 이미지 5*8 픽셀의 글자입니다.

LCD 컨트롤러에 따라 한번에 2픽셀씩 표현하는 경우에는 고민해서 적용하셔야할 것 같습니다.


이미지.xlsx



SSD1325 텍스트 작업 파일입니다.

SSD1325.xlsx


'초보의 아웅다웅 설계하기 > STM32' 카테고리의 다른 글

고정위치에 바이너리 라이팅하기  (0) 2018.08.17
IAR Debugger 다운로드 설정  (0) 2018.08.16
LCD 5*8 픽셀 글자  (0) 2018.07.27
Tamper 사용  (0) 2018.07.23
다중 이동식 저장장치  (0) 2018.07.23
USB Composite  (0) 2018.07.22
Posted by 초보 HW 엔지니어 로망와니

댓글을 달아 주세요

2018.07.23 15:28

내부 백업레지스터의 정보를 제거하는 용도로 사용하는 TAMPER 패리패럴을 설정하고 사용하는 방법입니다.

주요 정보를 저장해두고 유사시에 제거하는 용도로 사용하도록 설정하여 사용하면 될 것 같습니다.

TAMPER 핀은 PULL-DOWN해두고 유사시에 TAMPER 핀에 HIGH 신호를 주는 설정으로 하였습니다. 

전원 OFF 시에 전원이 TAMPER 핀으로 들어가지 않게 하기 위함이었습니다.



/*******************************************************************************

* Function Name : 

* Parameters    : 

* Return        : none

* Description   : 

*******************************************************************************/

void BackupRegister_Init(void)

{

NVIC_InitTypeDef NVIC_InitStructure;

/* Enable PWR and BKP clock */

RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR | RCC_APB1Periph_BKP, ENABLE);


/* Enable write access to Backup domain */

PWR_BackupAccessCmd(ENABLE);


/* Clear Tamper pin Event(TE) pending flag */

BKP_ClearFlag();


/* Enable Tamper pin */

BKP_TamperPinCmd(ENABLE);

/* Tamper pin active on low level */

BKP_TamperPinLevelConfig(BKP_TamperPinLevel_High);//BKP_TamperPinLevel_Low


/* Enable Tamper interrupt */

BKP_ITConfig(ENABLE);


  /* Enable TAMPER IRQChannel */

  NVIC_InitStructure.NVIC_IRQChannel = TAMPER_IRQn;

  NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;

  NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;

  NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;

  NVIC_Init(&NVIC_InitStructure);

  

UART1_printf("\r\n\n%X", BKP_ReadBackupRegister(BKP_DR1));

if (BKP_ReadBackupRegister(BKP_DR1) != 0xAAAA)

  {

    /* Backup data register value is not correct or not yet programmed (when

       the first time the program is executed) */


BKP_WriteBackupRegister(BKP_DR1, 0xAAAA);

UART1_printf("\r\n\n Write %X", BKP_ReadBackupRegister(BKP_DR1));

  }

  else

  {

    /* Check if the Power On Reset flag is set */

    if (RCC_GetFlagStatus(RCC_FLAG_PORRST) != RESET){

      UART1_printf("\r\n\n Power On Reset occurred....");

    }

    /* Check if the Pin Reset flag is set */

    else if (RCC_GetFlagStatus(RCC_FLAG_PINRST) != RESET){

      UART1_printf("\r\n\n External Reset occurred....");

    }

  }

  /* Clear reset flags */

  RCC_ClearFlag();

}





void TAMPER_IRQHandler(void)

{

  if(BKP_GetITStatus() != RESET)

  { /* Tamper detection event occured */



    /* Clear Tamper pin interrupt pending bit */

    BKP_ClearITPendingBit();


    /* Clear Tamper pin Event(TE) pending flag */

    BKP_ClearFlag();

  }

}

'초보의 아웅다웅 설계하기 > STM32' 카테고리의 다른 글

IAR Debugger 다운로드 설정  (0) 2018.08.16
LCD 5*8 픽셀 글자  (0) 2018.07.27
Tamper 사용  (0) 2018.07.23
다중 이동식 저장장치  (0) 2018.07.23
USB Composite  (0) 2018.07.22
error C1189: #error : MFC does not support WINVER less than 0x0501.  (0) 2018.07.18
Posted by 초보 HW 엔지니어 로망와니

댓글을 달아 주세요

2018.07.23 09:40

사용 MCU : STM32F103Zx

사용한 MassStorage 타입 :  SD, NandFlash, InterFlash


mass_mal.c에서 수정


#include "stm32f10x.h"

#include "stdio.h"

#include "bsp_sdio_sd.h"

#include "usr_nand.h"

#include "mass_mal.h"


#include "usr_led.h"

#include "usr_uart.h"


//#define MASSPRINT DEBUGPRINT

#define MASSPRINT(...)


typedef enum _MASS_ID

{

MASS_SD = 0,

MASS_NAND = 1,

MASS_INTERNNAL = 2,

}MASS_ID_E;


#define MAL_OK   0

#define MAL_FAIL 1

#define MAX_LUN  0 /* 0 SD, 1 SD, NAND Flash, 2 SD, NAND Flash, Internal Flash */


#define     FLASH_DISK_START_ADDRESS           0x08050000     /* Flash start address (10K for this bootloader) 0x08002800 -> 0x08060000 */

#define     FLASH_DISK_SIZE                0x20000        // 55296 -> 0xA000

#define     FLASH_PAGE_SIZE                       0x800         /* 1k -> 2K per page */

#define     WAIT_TIMEOUT                      100000 



uint32_t Mass_Memory_Size[3];

uint32_t Mass_Block_Size[3];

uint32_t Mass_Block_Count[3];


uint32_t Max_Lun = MAX_LUN;

/*******************************************************************************

* Function Name : 

* Parameters    : 

* Return        : none

* Description   : 

*******************************************************************************/

uint16_t MAL_Init(uint8_t lun)

{

uint16_t status = MAL_OK;

switch (lun)

{

case MASS_SD:

status = SD_Init();

if (status != SD_OK){

MASSPRINT("SD_Init() fail (%d) : file %s on line %d\r\n", status, __FILE__, __LINE__);

status = MAL_FAIL;

}

else{

MASSPRINT("SD_Init() Ok\r\n");

status = MAL_OK;

}

break;

case MASS_NAND:

if (NAND_Init() != NAND_OK){

MASSPRINT("NAND_Init() fail : file %s on line %d\r\n", __FILE__, __LINE__);

status = MAL_FAIL;

}

else{

MASSPRINT("NAND_Init() Ok\r\n");

status = MAL_OK;

}

break;

    case MASS_INTERNNAL:

FLASH_Unlock(); 

      break;

default:

break;

}

return status;

}


/*******************************************************************************

* Function Name : 

* Parameters    : 

* Return        : none

* Description   : 

*******************************************************************************/

uint16_t MAL_Write(uint8_t lun, uint32_t Memory_Offset, uint32_t *Writebuff, uint16_t Transfer_Length)

{

uint16_t status = MAL_OK;

uint16_t i;

switch (lun)

{

case MASS_SD:

status = SD_WriteBlock((uint8_t*)Writebuff, Memory_Offset, Transfer_Length);

if (status != SD_OK)

{

MASSPRINT("SD_WriteBlock(, 0x%X, 0x%X) Fail(%d) \r\n", Memory_Offset, Transfer_Length, status);

status = MAL_FAIL;

}

else

{

MASSPRINT("SD_WriteBlock(, 0x%X, 0x%X) Ok\r\n", Memory_Offset, Transfer_Length);

status = MAL_OK;

}

break;

case MASS_NAND:

if (NAND_Write(Memory_Offset, Writebuff, Transfer_Length) != NAND_OK)

{

MASSPRINT("NAND_Write(0x%X, ,0x%X) Fail\r\n", Memory_Offset, Transfer_Length);

status = MAL_FAIL;

}

else

{

MASSPRINT("NAND_Write(0x%X, ,0x%X) Ok\r\n", Memory_Offset, Transfer_Length);

status = MAL_OK;

}

break;

    case MASS_INTERNNAL:

for(i = 0; i < Transfer_Length; i += FLASH_PAGE_SIZE)

if (FLASH_WaitForLastOperation(WAIT_TIMEOUT) != FLASH_TIMEOUT)

{

FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR);

}

FLASH_ErasePage(FLASH_DISK_START_ADDRESS + Memory_Offset + i); 

}

 

for(i = 0; i < Transfer_Length; i += 4)

if(FLASH_WaitForLastOperation(WAIT_TIMEOUT) != FLASH_TIMEOUT)

{

FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPRTERR); 

FLASH_ProgramWord(FLASH_DISK_START_ADDRESS + Memory_Offset + i , Writebuff[i >> 2]); 

}

break;

 

default:

break;

}

return status;

}


/*******************************************************************************

* Function Name : 

* Parameters    : 

* Return        : none

* Description   : 

*******************************************************************************/

uint16_t MAL_Read(uint8_t lun, uint32_t Memory_Offset, uint32_t *Readbuff, uint16_t Transfer_Length)

{

uint16_t status = MAL_OK;

uint16_t i;

switch (lun)

{

case MASS_SD:

status = SD_ReadBlock((uint8_t*)Readbuff, Memory_Offset, Transfer_Length);

if (status != SD_OK)

{

MASSPRINT("SD_ReadBlock(, 0x%X, 0x%X) Fail(%d) \r\n", Memory_Offset, Transfer_Length, status);

status = MAL_FAIL;

}

else

{

MASSPRINT("SD_ReadBlock(, 0x%X, 0x%X) Ok\r\n", Memory_Offset, Transfer_Length);

status = MAL_OK;

}

break;

case MASS_NAND:

if (NAND_Read(Memory_Offset, Readbuff, Transfer_Length) != NAND_OK)

{

MASSPRINT("NAND_Read(0x%X, ,0x%X) Fail\r\n", Memory_Offset, Transfer_Length);

status = MAL_FAIL;

}

else

{

MASSPRINT("NAND_Read(0x%X, ,0x%X) Ok\r\n", Memory_Offset, Transfer_Length);

status = MAL_OK;

}

break;

    case MASS_INTERNNAL:

    for(i = 0; i < Transfer_Length; i += 4)

{

Readbuff[i >> 2] = ((vu32*)(FLASH_DISK_START_ADDRESS + Memory_Offset))[i >> 2]; 

}

      break;

default:

break;

}

return status;

}


/*******************************************************************************

* Function Name : 

* Parameters    : 

* Return        : none

* Description   : 

*******************************************************************************/

uint16_t MAL_GetStatus (uint8_t lun)

{

SD_CardInfo mSDCardInfo;

uint32_t DeviceSizeMul = 0, NumberOfBlocks = 0;

uint32_t nand_id;

uint16_t status = MAL_OK;

switch (lun)

{

case MASS_SD:

{

status = SD_Init();

if (status != SD_OK)

{

MASSPRINT("SD_Init() fail (%d) : file %s on line %d\r\n", status, __FILE__, __LINE__);

status = MAL_FAIL;

break;

}


SD_GetCardInfo(&mSDCardInfo);

SD_SelectDeselect((uint32_t) (mSDCardInfo.RCA << 16));

DeviceSizeMul = (mSDCardInfo.SD_csd.DeviceSizeMul + 2);

if (mSDCardInfo.CardType == SDIO_HIGH_CAPACITY_SD_CARD){

Mass_Block_Count[MASS_SD] = (mSDCardInfo.SD_csd.DeviceSize + 1) * 1024;

MASSPRINT("SD_GetCardInfo() Ok, SDHC Card\r\n");

}

else{

NumberOfBlocks  = ((1 << (mSDCardInfo.SD_csd.RdBlockLen)) / 512);

Mass_Block_Count[MASS_SD] = ((mSDCardInfo.SD_csd.DeviceSize + 1) * (1 << DeviceSizeMul) << (NumberOfBlocks/2));

MASSPRINT("SD_GetCardInfo() Ok, Normal SD Card\r\n");

}

Mass_Block_Size[MASS_SD]  = 512;

status = SD_SelectDeselect((uint32_t) (mSDCardInfo.RCA << 16)); 

status = SD_EnableWideBusOperation(SDIO_BusWide_4b); 

if (status != SD_OK){

MASSPRINT("SD_EnableWideBusOperation(SDIO_BusWide_4b) Fail (%d)\r\n", status);

status = MAL_FAIL;

break;

}

status = SD_SetDeviceMode(SD_DMA_MODE);    

if (status != SD_OK){

MASSPRINT("SD_SetDeviceMode(SD_DMA_MODE) Fail (%d)\r\n", status);

status = MAL_FAIL;

break;

Mass_Memory_Size[MASS_SD] = Mass_Block_Count[MASS_SD] * Mass_Block_Size[MASS_SD];

OUTPUT_On(OUTPUTPIN_2);

MASSPRINT("MAL_GetStatus(MASS_SD) Ok. Memory Size = %uMB\r\n", Mass_Memory_Size[0]/(1024*1024));

status = MAL_OK;

break;

}

case MASS_NAND:

{

nand_id = NAND_ReadID();


if ((nand_id != 0)

{


Mass_Block_Count[MASS_NAND] = NAND_ZONE_SIZE * NAND_BLOCK_SIZE * NAND_MAX_ZONE;

Mass_Block_Size[MASS_NAND]  = NAND_PAGE_SIZE;

Mass_Memory_Size[MASS_NAND] = (Mass_Block_Count[MASS_NAND] * Mass_Block_Size[MASS_NAND]);


OUTPUT_On(OUTPUTPIN_2);

MASSPRINT("MAL_GetStatus(MASS_NAND) Ok. Memory Size = %uMB\r\n", Mass_Memory_Size[MASS_NAND]/(1024*1024));

status = MAL_OK;

}

else

{

MASSPRINT("MAL_GetStatus(MASS_NAND) Fail\r\n");

status = MAL_FAIL;

}

break;

}

case MASS_INTERNNAL:

{    

Mass_Block_Count[MASS_INTERNNAL] = FLASH_DISK_SIZE / FLASH_PAGE_SIZE; 

      Mass_Block_Size[MASS_INTERNNAL] =  FLASH_PAGE_SIZE; 

      Mass_Memory_Size[MASS_INTERNNAL] = FLASH_DISK_SIZE; 

break;

}

default:

status = MAL_FAIL;

break;

}

return status;

}



'초보의 아웅다웅 설계하기 > STM32' 카테고리의 다른 글

LCD 5*8 픽셀 글자  (0) 2018.07.27
Tamper 사용  (0) 2018.07.23
다중 이동식 저장장치  (0) 2018.07.23
USB Composite  (0) 2018.07.22
error C1189: #error : MFC does not support WINVER less than 0x0501.  (0) 2018.07.18
Buzzer Melody  (0) 2018.07.16
Posted by 초보 HW 엔지니어 로망와니

댓글을 달아 주세요

2018.07.22 00:00

ConfigDescriptor의 설정과 다른 Endpoint에서 값을 가져오는 경우를 주의하여야 할 것 같습니다. 

빠르게 짜려고 긁어오다가 주로 실수하는 부분이라서...


USB Composite 드라이버를 올려야 해서 Endpoint를 더 가져올 경우 


/*-----------------------------------------------------------*/

usb_conf.h에서 사용할 Endpoint In/Out EPx_xxx_Callback 함수 주석처리

Endpoint ADDR을 추가


#define BTABLE_ADDRESS      (0x00)


/* EP0  */

/* rx/tx buffer base address */

#define ENDP0_RXADDR        (0x18)

#define ENDP0_TXADDR        (0x58)


/* EP1  */

/* tx buffer base address */

//#define ENDP1_TXADDR        (0x98)

#define ENDP1_TXADDR        (0x98)

#define ENDP1_RXADDR        (0xD8)


/* EP2  */

/* Rx buffer base address */

//#define ENDP2_RXADDR        (0xD8)

#define ENDP2_TXADDR        (0x118)

#define ENDP2_RXADDR        (0x158)


/* CTR service routines */

/* associated to defined endpoints */

//#define  EP1_IN_Callback   NOP_Process

//#define  EP2_IN_Callback   NOP_Process

#define  EP3_IN_Callback   NOP_Process

#define  EP4_IN_Callback   NOP_Process

#define  EP5_IN_Callback   NOP_Process

#define  EP6_IN_Callback   NOP_Process

#define  EP7_IN_Callback   NOP_Process



//#define  EP1_OUT_Callback   NOP_Process

//#define  EP2_OUT_Callback   NOP_Process

#define  EP3_OUT_Callback  NOP_Process

#define  EP4_OUT_Callback   NOP_Process

#define  EP5_OUT_Callback   NOP_Process

#define  EP6_OUT_Callback   NOP_Process

#define  EP7_OUT_Callback   NOP_Process


/*-----------------------------------------------------------*/

usb_endp.c에 Callback를 넣고 처리할 부분 추가

void EP1_OUT_Callback(void)

{

  PMAToUserBufferCopy(Receive_Buffer, ENDP1_RXADDR, 2);

  if (Receive_Buffer[1] == 0)

  {

  }

  else 

  {

  }

}


void EP1_IN_Callback(void)

{

}


void EP2_IN_Callback(void)

{

}


void EP2_OUT_Callback(void)

{

}


/*-----------------------------------------------------------*/

usb_desc.c 및 h 변경


/* Includes ------------------------------------------------------------------*/
#include "usb_desc.h"
#define  DEV_DSC_VID0 0x83
#define  DEV_DSC_VID1 0x04

#define  DEV_DSC_PID0 0x20
#define  DEV_DSC_PID1 0x57

#define USB_DEVICE_DESCRIPTOR_TYPE              0x01
#define USB_OTG_HS_MAX_PACKET_SIZE           512
#define USB_OTG_FS_MAX_PACKET_SIZE           64
#define USB_OTG_MAX_EP0_SIZE                 64

#define USB_DEVICE_DESCRIPTOR_TYPE              0x01
#define USB_CONFIGURATION_DESCRIPTOR_TYPE       0x02
#define USB_STRING_DESCRIPTOR_TYPE              0x03
#define USB_INTERFACE_DESCRIPTOR_TYPE           0x04
#define USB_ENDPOINT_DESCRIPTOR_TYPE            0x05

#define HID_DESCRIPTOR_TYPE                     0x21
#define CUSTOMHID_SIZ_HID_DESC                  0x09
#define CUSTOMHID_OFF_HID_DESC                  0x12

#define Composite_SIZ_DEVICE_DESC               18
#define Composite_SIZ_CONFIG_DESC               66//64
#define CUSTOMHID_SIZ_REPORT_DESC               162
#define Composite_SIZ_STRING_LANGID             4
#define Composite_SIZ_STRING_VENDOR             28
#define Composite_SIZ_STRING_PRODUCT            48
#define Composite_SIZ_STRING_SERIAL             34
#define Composite_SIZ_STRING_INTERFACE         42

#define STANDARD_ENDPOINT_DESC_SIZE             0x09

const uint8_t Composite_DeviceDescriptor[Composite_SIZ_DEVICE_DESC] =
  {
    0x12,                       /*bLength */
    USB_DEVICE_DESCRIPTOR_TYPE, /*bDescriptorType*/
    0x00,                       /*bcdUSB */
    0x02,
    0x00,                       /*bDeviceClass*/
    0x00,                       /*bDeviceSubClass*/
    0x00,                       /*bDeviceProtocol*/
    USB_OTG_MAX_EP0_SIZE,   /* bMaxPacketSize0 0x40 = 64 */
DEV_DSC_VID0,   /* idVendor */
    DEV_DSC_VID1,
    DEV_DSC_PID0,   /* idProduct */
    DEV_DSC_PID1,
    0x00,                       /*bcdDevice rel. 2.00*/
    0x02,
    1,                          /*Index of string descriptor describing
                                              manufacturer */
    2,                          /*Index of string descriptor describing
                                             product*/
    3,                          /*Index of string descriptor describing the
                                             device serial number */
    0x01                        /*bNumConfigurations*/
  }
  ; /* Composite_DeviceDescriptor */


/* USB Configuration Descriptor */
/*   All Descriptors (Configuration, Interface, Endpoint, Class, Vendor */
const uint8_t Composite_ConfigDescriptor[Composite_SIZ_CONFIG_DESC] =
  {
    0x09, /* bLength: Configuration Descriptor size */
    USB_CONFIGURATION_DESCRIPTOR_TYPE, /* bDescriptorType: Configuration */
    Composite_SIZ_CONFIG_DESC,
    /* wTotalLength: Bytes returned */
    0x00,
    0x02,         /* bNumInterfaces: 2 interfaces */
    0x01,         /* bConfigurationValue: Configuration value */
    0x00,         /* iConfiguration: Index of string descriptor describing
                                 the configuration*/
    0xC0,         /* bmAttributes: Self powered */
    0x32,         /* MaxPower 100 mA: this current is used for detecting Vbus */

    /************** Descriptor of Custom HID interface ****************/
    /* 09 */
    0x09,         /* bLength: Interface Descriptor size */
    USB_INTERFACE_DESCRIPTOR_TYPE,/* bDescriptorType: Interface descriptor type */
    0x00,         /* bInterfaceNumber: Number of Interface */
    0x00,         /* bAlternateSetting: Alternate setting */
    0x02,         /* bNumEndpoints */
    0x03,         /* bInterfaceClass: HID */
    0x00,         /* bInterfaceSubClass : 1=BOOT, 0=no boot */
    0x00,         /* nInterfaceProtocol : 0=none, 1=keyboard, 2=mouse */
    2,//0,            /* iInterface: Index of string descriptor */
    /******************** Descriptor of Custom HID HID ********************/
    /* 18 */
    0x09,         /* bLength: HID Descriptor size */
    HID_DESCRIPTOR_TYPE, /* bDescriptorType: HID */
    0x10,         /* bcdHID: HID Class Spec release number */
    0x01,
    0x00,         /* bCountryCode: Hardware target country */
    0x01,         /* bNumDescriptors: Number of HID class descriptors to follow */
    0x22,         /* bDescriptorType */
    CUSTOMHID_SIZ_REPORT_DESC,/* wItemLength: Total length of Report descriptor */
    0x00,
    /******************** Descriptor of Custom HID endpoints ******************/
    /* 27 */
    0x07,          /* bLength: Endpoint Descriptor size */
    USB_ENDPOINT_DESCRIPTOR_TYPE, /* bDescriptorType: */

    0x81,          /* bEndpointAddress: Endpoint Address (IN) 0x81 */
    0x03,          /* bmAttributes: Interrupt endpoint */
    0x02,          /* wMaxPacketSize: 2 Bytes max */
    0x00,
    0x20,          /* bInterval: Polling Interval (32 ms) */
    /* 34 */
   
    0x07, /* bLength: Endpoint Descriptor size */
    USB_ENDPOINT_DESCRIPTOR_TYPE, /* bDescriptorType: */
/* Endpoint descriptor type */
    0x01, /* bEndpointAddress: */
/* Endpoint Address (OUT) */
    0x03, /* bmAttributes: Interrupt endpoint */
    0x02, /* wMaxPacketSize: 2 Bytes max  */
    0x00,
    0x20, /* bInterval: Polling Interval (20 ms) */
    /* 41 */
    /******************** Descriptor of Mass Storage interface ********************/
    /* 09 */
    0x09,   /* bLength: Interface Descriptor size */
    USB_INTERFACE_DESCRIPTOR_TYPE,   /* bDescriptorType: */
    /*      Interface descriptor type */
    0x01,   /* bInterfaceNumber: Number of Interface */ //0x00 => 0x01
    0x00,   /* bAlternateSetting: Alternate setting */
    0x02,   /* bNumEndpoints*/
    0x08,   /* bInterfaceClass: MASS STORAGE Class */
    0x06,   /* bInterfaceSubClass : SCSI transparent*/
    0x50,   /* nInterfaceProtocol */
    0X04,          /* iInterface: */ //4 ->1
    /* 18 */
    0x07,   /*Endpoint descriptor length = 7*/
    0x05,   /*Endpoint descriptor type */
    0x82,   /*Endpoint address (IN, address 1) *///0x81
    0x02,   /*Bulk endpoint type */
    0x40,   /*Maximum packet size (64 bytes) */
    0x00,
    0x00,   /*Polling interval in milliseconds */
    /* 25 */
    0x07,   /*Endpoint descriptor length = 7 */
    0x05,   /*Endpoint descriptor type */
    0x02,   /*Endpoint address (OUT, address 2) */
    0x02,   /*Bulk endpoint type */
    0x40,   /*Maximum packet size (64 bytes) */
    0x00,
    0x00     /*Polling interval in milliseconds*/
    /*32*/
  }; /* Composite_ConfigDescriptor */
const uint8_t CustomHID_ReportDescriptor[CUSTOMHID_SIZ_REPORT_DESC] =
  {                    
    0x05, 0x8c,            /* USAGE_PAGE (ST Page)           */                   
    0x09, 0x01,            /* USAGE (Demo Kit)               */    
    0xa1, 0x01,            /* COLLECTION (Application)       */            
    /* 6 */
    
    /* Led 1 */        
    0x85, 0x01,            /*     REPORT_ID (1)      */
    0x09, 0x01,            /*     USAGE (LED 1)              */
    0x15, 0x00,            /*     LOGICAL_MINIMUM (0)        */          
    0x25, 0x01,            /*     LOGICAL_MAXIMUM (1)        */           
    0x75, 0x08,            /*     REPORT_SIZE (8)            */        
    0x95, 0x01,            /*     REPORT_COUNT (1)           */       
    0xB1, 0x82,             /*    FEATURE (Data,Var,Abs,Vol) */     

    0x85, 0x01,            /*     REPORT_ID (1)              */
    0x09, 0x01,            /*     USAGE (LED 1)              */
    0x91, 0x82,            /*     OUTPUT (Data,Var,Abs,Vol)  */
    /* 26 */
    
    /* Led 2 */
    0x85, 0x02,            /*     REPORT_ID 2      */
    0x09, 0x02,            /*     USAGE (LED 2)              */
    0x15, 0x00,            /*     LOGICAL_MINIMUM (0)        */          
    0x25, 0x01,            /*     LOGICAL_MAXIMUM (1)        */           
    0x75, 0x08,            /*     REPORT_SIZE (8)            */        
    0x95, 0x01,            /*     REPORT_COUNT (1)           */       
    0xB1, 0x82,             /*    FEATURE (Data,Var,Abs,Vol) */     

    0x85, 0x02,            /*     REPORT_ID (2)              */
    0x09, 0x02,            /*     USAGE (LED 2)              */
    0x91, 0x82,            /*     OUTPUT (Data,Var,Abs,Vol)  */
    /* 46 */
    
    /* Led 3 */        
    0x85, 0x03,            /*     REPORT_ID (3)      */
    0x09, 0x03,            /*     USAGE (LED 3)              */
    0x15, 0x00,            /*     LOGICAL_MINIMUM (0)        */          
    0x25, 0x01,            /*     LOGICAL_MAXIMUM (1)        */           
    0x75, 0x08,            /*     REPORT_SIZE (8)            */        
    0x95, 0x01,            /*     REPORT_COUNT (1)           */       
    0xB1, 0x82,             /*    FEATURE (Data,Var,Abs,Vol) */     

    0x85, 0x03,            /*     REPORT_ID (3)              */
    0x09, 0x03,            /*     USAGE (LED 3)              */
    0x91, 0x82,            /*     OUTPUT (Data,Var,Abs,Vol)  */
    /* 66 */
    
    /* Led 4 */
    0x85, 0x04,            /*     REPORT_ID 4)      */
    0x09, 0x04,            /*     USAGE (LED 4)              */
    0x15, 0x00,            /*     LOGICAL_MINIMUM (0)        */          
    0x25, 0x01,            /*     LOGICAL_MAXIMUM (1)        */           
    0x75, 0x08,            /*     REPORT_SIZE (8)            */        
    0x95, 0x01,            /*     REPORT_COUNT (1)           */       
    0xB1, 0x82,            /*     FEATURE (Data,Var,Abs,Vol) */     

    0x85, 0x04,            /*     REPORT_ID (4)              */
    0x09, 0x04,            /*     USAGE (LED 4)              */
    0x91, 0x82,            /*     OUTPUT (Data,Var,Abs,Vol)  */
    /* 86 */
    
    /* key Push Button */  
    0x85, 0x05,            /*     REPORT_ID (5)              */
    0x09, 0x05,            /*     USAGE (Push Button)        */      
    0x15, 0x00,            /*     LOGICAL_MINIMUM (0)        */      
    0x25, 0x01,            /*     LOGICAL_MAXIMUM (1)        */      
    0x75, 0x01,            /*     REPORT_SIZE (1)            */  
    0x81, 0x82,            /*     INPUT (Data,Var,Abs,Vol)   */   
    
    0x09, 0x05,            /*     USAGE (Push Button)        */               
    0x75, 0x01,            /*     REPORT_SIZE (1)            */           
    0xb1, 0x82,            /*     FEATURE (Data,Var,Abs,Vol) */  
         
    0x75, 0x07,            /*     REPORT_SIZE (7)            */           
    0x81, 0x83,            /*     INPUT (Cnst,Var,Abs,Vol)   */                    
    0x85, 0x05,            /*     REPORT_ID (2)              */         
                    
    0x75, 0x07,            /*     REPORT_SIZE (7)            */           
    0xb1, 0x83,            /*     FEATURE (Cnst,Var,Abs,Vol) */                      
    /* 114 */

    /* Tamper Push Button */  
    0x85, 0x06,            /*     REPORT_ID (6)              */
    0x09, 0x06,            /*     USAGE (Tamper Push Button) */      
    0x15, 0x00,            /*     LOGICAL_MINIMUM (0)        */      
    0x25, 0x01,            /*     LOGICAL_MAXIMUM (1)        */      
    0x75, 0x01,            /*     REPORT_SIZE (1)            */  
    0x81, 0x82,            /*     INPUT (Data,Var,Abs,Vol)   */   
    
    0x09, 0x06,            /*     USAGE (Tamper Push Button) */               
    0x75, 0x01,            /*     REPORT_SIZE (1)            */           
    0xb1, 0x82,            /*     FEATURE (Data,Var,Abs,Vol) */  
         
    0x75, 0x07,            /*     REPORT_SIZE (7)            */           
    0x81, 0x83,            /*     INPUT (Cnst,Var,Abs,Vol)   */                    
    0x85, 0x06,            /*     REPORT_ID (6)              */         
                    
    0x75, 0x07,            /*     REPORT_SIZE (7)            */           
    0xb1, 0x83,            /*     FEATURE (Cnst,Var,Abs,Vol) */  
    /* 142 */
    
    /* ADC IN */
    0x85, 0x07,            /*     REPORT_ID (7)              */         
    0x09, 0x07,            /*     USAGE (ADC IN)             */          
    0x15, 0x00,            /*     LOGICAL_MINIMUM (0)        */               
    0x26, 0xff, 0x00,      /*     LOGICAL_MAXIMUM (255)      */                 
    0x75, 0x08,            /*     REPORT_SIZE (8)            */           
    0x81, 0x82,            /*     INPUT (Data,Var,Abs,Vol)   */                    
    0x85, 0x07,            /*     REPORT_ID (7)              */                 
    0x09, 0x07,            /*     USAGE (ADC in)             */                     
    0xb1, 0x82,            /*     FEATURE (Data,Var,Abs,Vol) */                                 
    /* 161 */

    0xc0           /*     END_COLLECTION              */
  }; /* CustomHID_ReportDescriptor */
/* USB String Descriptors (optional) */
const uint8_t Composite_StringLangID[Composite_SIZ_STRING_LANGID] =
{
Composite_SIZ_STRING_LANGID,
USB_STRING_DESCRIPTOR_TYPE,
0x09,
0x04
}; /* LangID = 0x0409: U.S. English */

const uint8_t Composite_StringVendor[Composite_SIZ_STRING_VENDOR] =
  {
    Composite_SIZ_STRING_VENDOR, /* Size of manufacturer string */
    0x03,           /* bDescriptorType = String descriptor */
    /* Manufacturer: "STMicroelectronics" */
    ' ', 0, ' ', 0, ' ', 0, ' ', 0, ' ', 0, ' ', 0, ' ', 0, ' ', 0, //16
    ' ', 0, ' ', 0, ' ', 0, ' ', 0, ' ', 0 //10
  };
const uint8_t Composite_StringProduct[Composite_SIZ_STRING_PRODUCT] =
{
Composite_SIZ_STRING_PRODUCT,          /* bLength */
USB_STRING_DESCRIPTOR_TYPE,        /* bDescriptorType */
' ', 0, ' ', 0, ' ', 0, ' ', 0, ' ', 0, ' ', 0, 'C', 0,
'o', 0, 'm', 0, 'p', 0, 'o', 0, 's', 0, 'i', 0, 't', 0,
'e', 0,' ',0, 'M', 0, 'S', 0, 'C', 0, '+', 0, 'H', 0, 'I', 0, 'D', 0
};

uint8_t Composite_StringSerial[Composite_SIZ_STRING_SERIAL] =
  {
    Composite_SIZ_STRING_SERIAL,
    0x03,
    /* Serial number*/
    '0',0x00,'0',0x00,'0',0x00,'0',0x00,'0',0x00,'0',0x00,
'0',0x00,'0',0x00,'0',0x00,'0',0x00,'0',0x00,'0',0x00,
'0',0x00,'0',0x00,'0',0x00,'0',0x00
  };

const uint8_t Composite_StringInterface[Composite_SIZ_STRING_INTERFACE] =
  {
    Composite_SIZ_STRING_INTERFACE,
    0x03,
    /* Interface 0: "ST Mass" */
    ' ',0x00,' ',0x00,' ',0x00,' ',0x00,
    ' ',0x00,' ',0x00,' ',0x00,' ',0x00,
    ' ',0x00,' ',0x00,' ',0x00,' ',0x00,
    ' ',0x00,' ',0x00,' ',0x00,' ',0x00,
    ' ',0x00,' ',0x00,' ',0x00,' ',0x00
  };

usb_prop.c

/******************** (C) COPYRIGHT 2011 STMicroelectronics ********************
* File Name          : usb_prop.c
* Author             : MCD Application Team
* Version            : V3.3.0
* Date               : 21-March-2011
* Description        : All processing related to Mass Storage Demo
********************************************************************************
* THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS
* WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE TIME.
* AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY DIRECT,
* INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING FROM THE
* CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE CODING
* INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS.
*******************************************************************************/

/* Includes ------------------------------------------------------------------*/
#include "usb_lib.h"
#include "usb_desc.h"
#include "usb_pwr.h"
#include "usb_bot.h"
#include "usb_hw.h"
#include "memory.h"
#include "mass_mal.h"
#include "usb_prop.h"

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/


DEVICE Device_Table =
  {
    EP_NUM,
    2
  };

DEVICE_PROP Device_Property =
  {
    CustomHID_init,
    CustomHID_Reset,
    CustomHID_Status_In,
    CustomHID_Status_Out,
    CustomHID_Data_Setup,
    CustomHID_NoData_Setup,
    CustomHID_Get_Interface_Setting,
    CustomHID_GetDeviceDescriptor,
    CustomHID_GetConfigDescriptor,
    CustomHID_GetStringDescriptor,
    0,
    0x40 /*MAX PACKET SIZE*/
  };
USER_STANDARD_REQUESTS User_Standard_Requests =
  {
    CustomHID_GetConfiguration,
    CustomHID_SetConfiguration,
    CustomHID_GetInterface,
    CustomHID_SetInterface,
    CustomHID_GetStatus,
    CustomHID_ClearFeature,
    CustomHID_SetEndPointFeature,
    CustomHID_SetDeviceFeature,
    CustomHID_SetDeviceAddress
  };

ONE_DESCRIPTOR Device_Descriptor =
  {
    (uint8_t*)Composite_DeviceDescriptor,
    Composite_SIZ_DEVICE_DESC
  };

ONE_DESCRIPTOR Config_Descriptor =
  {
    (uint8_t*)Composite_ConfigDescriptor,
    Composite_SIZ_CONFIG_DESC
  };

ONE_DESCRIPTOR CustomHID_Report_Descriptor =
  {
    (uint8_t *)CustomHID_ReportDescriptor,
    CUSTOMHID_SIZ_REPORT_DESC
  };

ONE_DESCRIPTOR CustomHID_Hid_Descriptor =
  {
    (uint8_t*)Composite_ConfigDescriptor + CUSTOMHID_OFF_HID_DESC,
    CUSTOMHID_SIZ_HID_DESC
  };

ONE_DESCRIPTOR String_Descriptor[5] =
  {
    {(uint8_t*)Composite_StringLangID, Composite_SIZ_STRING_LANGID},
    {(uint8_t*)Composite_StringVendor, Composite_SIZ_STRING_VENDOR},
    {(uint8_t*)Composite_StringProduct, Composite_SIZ_STRING_PRODUCT},
    {(uint8_t*)Composite_StringSerial, Composite_SIZ_STRING_SERIAL},
    {(uint8_t*)Composite_StringInterface, Composite_SIZ_STRING_INTERFACE}
  };

uint8_t *CustomHID_SetReport_Feature(uint16_t Length);
/* Extern variables ----------------------------------------------------------*/
extern unsigned char Bot_State;
extern Bulk_Only_CBW CBW;

/* Private function prototypes -----------------------------------------------*/
/* Extern function prototypes ------------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/*******************************************************************************
* Function Name  : MASS_init
* Description    : Mass Storage init routine.
* Input          : None.
* Output         : None.
* Return         : None.
*******************************************************************************/
void CustomHID_init()
{
  /* Update the serial number string descriptor with the data from the unique
  ID*/
  Get_SerialNum();

  pInformation->Current_Configuration = 0;

  /* Connect the device */
  PowerOn();

  /* Perform basic device initialization operations */
  USB_SIL_Init();

  bDeviceState = UNCONNECTED;
}

/*******************************************************************************
* Function Name  : MASS_Reset
* Description    : Mass Storage reset routine.
* Input          : None.
* Output         : None.
* Return         : None.
*******************************************************************************/
void CustomHID_Reset()
{
  /* Set the device as not configured */
  pInformation->Current_Configuration = 0;
  pInformation->Current_Interface = 0;/*the default Interface*/

  /* Current Feature initialization */
  pInformation->Current_Feature = Composite_ConfigDescriptor[7];

#ifdef STM32F10X_CL   
  
  /* EP0 is already configured by USB_SIL_Init() function */

  /* Init EP1 IN as Bulk endpoint */
  OTG_DEV_EP_Init(EP1_IN, OTG_DEV_EP_TYPE_BULK, BULK_MAX_PACKET_SIZE);
  
  /* Init EP2 OUT as Bulk endpoint */
  OTG_DEV_EP_Init(EP2_OUT, OTG_DEV_EP_TYPE_BULK, BULK_MAX_PACKET_SIZE); 
  
#else 

  SetBTABLE(BTABLE_ADDRESS);

  /* Initialize Endpoint 0 */
  SetEPType(ENDP0, EP_CONTROL);
  SetEPTxStatus(ENDP0, EP_TX_STALL);//  SetEPTxStatus(ENDP0, EP_TX_NAK);
  SetEPRxAddr(ENDP0, ENDP0_RXADDR);
  SetEPRxCount(ENDP0, Device_Property.MaxPacketSize);
  SetEPTxAddr(ENDP0, ENDP0_TXADDR);
  Clear_Status_Out(ENDP0);
  SetEPRxValid(ENDP0);

/* HID */
  SetEPType(ENDP1, EP_INTERRUPT);
  SetEPTxAddr(ENDP1, ENDP1_TXADDR);
  SetEPRxAddr(ENDP1, ENDP1_RXADDR);
  SetEPTxCount(ENDP1, 2);
  SetEPRxCount(ENDP1, 2);
  SetEPRxStatus(ENDP1, EP_RX_VALID);
  SetEPTxStatus(ENDP1, EP_TX_NAK);

/* Massstorage */
/* Initialize Endpoint 1 */
  SetEPType(ENDP2, EP_BULK);
  SetEPTxCount(ENDP2, Device_Property.MaxPacketSize);
  SetEPTxAddr(ENDP2, ENDP1_TXADDR);
  SetEPTxStatus(ENDP2, EP_TX_NAK);
  SetEPRxStatus(ENDP2, EP_RX_DIS);

  /* Initialize Endpoint 2 */
  SetEPType(ENDP2, EP_BULK);
  SetEPRxAddr(ENDP2, ENDP2_RXADDR);
  SetEPRxCount(ENDP2, Device_Property.MaxPacketSize);
  SetEPRxStatus(ENDP2, EP_RX_VALID);
  SetEPTxStatus(ENDP2, EP_TX_DIS);
  
  /* Set the device to response on default address */
  SetDeviceAddress(0);
#endif /* STM32F10X_CL */

  bDeviceState = ATTACHED;

  CBW.dSignature = BOT_CBW_SIGNATURE;
  Bot_State = BOT_IDLE;

  USB_NotConfigured_LED();
}

/*******************************************************************************
* Function Name  : Mass_Storage_SetConfiguration
* Description    : Handle the SetConfiguration request.
* Input          : None.
* Output         : None.
* Return         : None.
*******************************************************************************/
void CustomHID_SetConfiguration(void)
{
  if (pInformation->Current_Configuration != 0)
  {
    /* Device configured */
    bDeviceState = CONFIGURED;

#ifdef STM32F10X_CL 
    /* Init EP1 IN as Bulk endpoint */
    OTG_DEV_EP_Init(EP1_IN, OTG_DEV_EP_TYPE_BULK, BULK_MAX_PACKET_SIZE);
  
    /* Init EP2 OUT as Bulk endpoint */
    OTG_DEV_EP_Init(EP2_OUT, OTG_DEV_EP_TYPE_BULK, BULK_MAX_PACKET_SIZE);     
#else    
/* HID */
    ClearDTOG_RX(ENDP2);
    ClearDTOG_TX(ENDP1);
/* MassStorage */
    ClearDTOG_TX(ENDP1);
    ClearDTOG_RX(ENDP2);
#endif /* STM32F10X_CL */

    Bot_State = BOT_IDLE; /* set the Bot state machine to the IDLE state */
  }
}

/*******************************************************************************
* Function Name  : Mass_Storage_ClearFeature
* Description    : Handle the ClearFeature request.
* Input          : None.
* Output         : None.
* Return         : None.
*******************************************************************************/
void CustomHID_ClearFeature(void)//
{
  /* when the host send a CBW with invalid signature or invalid length the two
     Endpoints (IN & OUT) shall stall until receiving a Mass Storage Reset     */
  if (CBW.dSignature != BOT_CBW_SIGNATURE)
    Bot_Abort(BOTH_DIR);
}

/*******************************************************************************
* Function Name  : Mass_Storage_SetConfiguration.
* Description    : Update the device state to addressed.
* Input          : None.
* Output         : None.
* Return         : None.
*******************************************************************************/
void CustomHID_SetDeviceAddress (void)
{
  bDeviceState = ADDRESSED;
}
/*******************************************************************************
* Function Name  : CustomHID_Status_In.
* Description    : Joystick status IN routine.
* Input          : None.
* Output         : None.
* Return         : None.
*******************************************************************************/
void CustomHID_Status_In(void)
{  
  return;
}

/*******************************************************************************
* Function Name  : CustomHID_Status_Out
* Description    : Joystick status OUT routine.
* Input          : None.
* Output         : None.
* Return         : None.
*******************************************************************************/
void CustomHID_Status_Out (void)
{
  return;
}

/*******************************************************************************
* Function Name  : MASS_Status_In
* Description    : Mass Storage Status IN routine.
* Input          : None.
* Output         : None.
* Return         : None.
*******************************************************************************/
void MASS_Status_In(void)
{
  return;
}

/*******************************************************************************
* Function Name  : MASS_Status_Out
* Description    : Mass Storage Status OUT routine.
* Input          : None.
* Output         : None.
* Return         : None.
*******************************************************************************/
void MASS_Status_Out(void)
{
  return;
}

/*******************************************************************************
* Function Name  : MASS_Data_Setup.
* Description    : Handle the data class specific requests..
* Input          : RequestNo.
* Output         : None.
* Return         : RESULT.
*******************************************************************************/
RESULT CustomHID_Data_Setup(uint8_t RequestNo)
{
  uint8_t *(*CopyRoutine)(uint16_t);
    
  CopyRoutine = NULL;
  
  if ((RequestNo == GET_DESCRIPTOR)
      && (Type_Recipient == (STANDARD_REQUEST | INTERFACE_RECIPIENT)))
{    
    if(pInformation->USBwIndex0 == 0)
    {
      if (pInformation->USBwValue1 == REPORT_DESCRIPTOR)
      {
        CopyRoutine = CustomHID_GetReportDescriptor;
      }
      else if (pInformation->USBwValue1 == HID_DESCRIPTOR_TYPE)
      {
        CopyRoutine = CustomHID_GetHIDDescriptor;
      }
    }
  } /* End of GET_DESCRIPTOR */
  else if ((Type_Recipient == (CLASS_REQUEST | INTERFACE_RECIPIENT))
           && RequestNo == GET_PROTOCOL)
  {
    CopyRoutine = CustomHID_GetProtocolValue;
  }
if ((Type_Recipient == (CLASS_REQUEST | INTERFACE_RECIPIENT))
      && (RequestNo == GET_MAX_LUN) && (pInformation->USBwValue == 0)
      && (pInformation->USBwIndex == 0) && (pInformation->USBwLength == 0x01))
  {
    CopyRoutine = Get_Max_Lun;
  }
  
  if (CopyRoutine == NULL){
    return USB_UNSUPPORT;
  }
  
  pInformation->Ctrl_Info.CopyData = CopyRoutine;
  pInformation->Ctrl_Info.Usb_wOffset = 0;
  (*CopyRoutine)(0);
  return USB_SUCCESS;
}

/*******************************************************************************
* Function Name  : MASS_NoData_Setup.
* Description    : Handle the no data class specific requests.
* Input          : RequestNo.
* Output         : None.
* Return         : RESULT.
*******************************************************************************/
RESULT CustomHID_NoData_Setup(uint8_t RequestNo)
{
  if ((Type_Recipient == (CLASS_REQUEST | INTERFACE_RECIPIENT))
      && (RequestNo == SET_PROTOCOL))
  {
   #ifdef STM32F10X_CL 
    /* Init EP1 IN as Bulk endpoint */
    OTG_DEV_EP_Init(EP1_IN, OTG_DEV_EP_TYPE_BULK, BULK_MAX_PACKET_SIZE);
  
    /* Init EP2 OUT as Bulk endpoint */
    OTG_DEV_EP_Init(EP2_OUT, OTG_DEV_EP_TYPE_BULK, BULK_MAX_PACKET_SIZE);     
   #else
/* HID */
    ClearDTOG_RX(ENDP2);
    ClearDTOG_TX(ENDP1);
/* MassStorage */
    ClearDTOG_TX(ENDP1);
    ClearDTOG_RX(ENDP2);
   #endif /* STM32F10X_CL */

    /*initialize the CBW signature to enable the clear feature*/
    CBW.dSignature = BOT_CBW_SIGNATURE;
    Bot_State = BOT_IDLE;

    return CustomHID_SetProtocol();
  }
  return USB_UNSUPPORT;
}

/*******************************************************************************
* Function Name  : MASS_Get_Interface_Setting
* Description    : Test the interface and the alternate setting according to the
*                  supported one.
* Input          : uint8_t Interface, uint8_t AlternateSetting.
* Output         : None.
* Return         : RESULT.
*******************************************************************************/
RESULT CustomHID_Get_Interface_Setting(uint8_t Interface, uint8_t AlternateSetting)
{
  if (AlternateSetting > 0)
  {
    return USB_UNSUPPORT;/* in this application we don't have AlternateSetting*/
  }
  else if (Interface > 0)
  {
    return USB_UNSUPPORT;/*in this application we have only 1 interfaces*/
  }
  return USB_SUCCESS;
}

/*******************************************************************************
* Function Name  : MASS_GetDeviceDescriptor
* Description    : Get the device descriptor.
* Input          : uint16_t Length.
* Output         : None.
* Return         : None.
*******************************************************************************/
uint8_t *CustomHID_GetDeviceDescriptor(uint16_t Length)
{
  return Standard_GetDescriptorData(Length, &Device_Descriptor );
}

/*******************************************************************************
* Function Name  : MASS_GetConfigDescriptor
* Description    : Get the configuration descriptor.
* Input          : uint16_t Length.
* Output         : None.
* Return         : None.
*******************************************************************************/
uint8_t *CustomHID_GetConfigDescriptor(uint16_t Length)
{
  return Standard_GetDescriptorData(Length, &Config_Descriptor );
}

/*******************************************************************************
* Function Name  : MASS_GetStringDescriptor
* Description    : Get the string descriptors according to the needed index.
* Input          : uint16_t Length.
* Output         : None.
* Return         : None.
*******************************************************************************/
uint8_t *CustomHID_GetStringDescriptor(uint16_t Length)
{
  uint8_t wValue0 = pInformation->USBwValue0;

//  if (wValue0 > 5)
  if (wValue0 > 4)
  {
    return NULL;
  }
  else
  {
    return Standard_GetDescriptorData(Length, &String_Descriptor[wValue0]);
  }
}

uint32_t ProtocolValue;
uint8_t Report_Buf[2];  
/*******************************************************************************
* Function Name  : CustomHID_SetReport_Feature
* Description    : Set Feature request handling
* Input          : Length.
* Output         : None.
* Return         : Buffer
*******************************************************************************/
uint8_t *CustomHID_SetReport_Feature(uint16_t Length)
{
  if (Length == 0)
  {
    pInformation->Ctrl_Info.Usb_wLength = 2;
    return NULL;
  }
  else
  {
    return Report_Buf;
  }
}

/*******************************************************************************
* Function Name  : CustomHID_GetReportDescriptor.
* Description    : Gets the HID report descriptor.
* Input          : Length
* Output         : None.
* Return         : The address of the configuration descriptor.
*******************************************************************************/
uint8_t *CustomHID_GetReportDescriptor(uint16_t Length)
{
  return Standard_GetDescriptorData(Length, &CustomHID_Report_Descriptor);
}

/*******************************************************************************
* Function Name  : CustomHID_GetHIDDescriptor.
* Description    : Gets the HID descriptor.
* Input          : Length
* Output         : None.
* Return         : The address of the configuration descriptor.
*******************************************************************************/
uint8_t *CustomHID_GetHIDDescriptor(uint16_t Length)
{
  return Standard_GetDescriptorData(Length, &CustomHID_Hid_Descriptor);
}

/*******************************************************************************
* Function Name  : CustomHID_SetProtocol
* Description    : Joystick Set Protocol request routine.
* Input          : None.
* Output         : None.
* Return         : USB SUCCESS.
*******************************************************************************/
RESULT CustomHID_SetProtocol(void)
{
  uint8_t wValue0 = pInformation->USBwValue0;
  ProtocolValue = wValue0;
  return USB_SUCCESS;
}

/*******************************************************************************
* Function Name  : CustomHID_GetProtocolValue
* Description    : get the protocol value
* Input          : Length.
* Output         : None.
* Return         : address of the protocol value.
*******************************************************************************/
uint8_t *CustomHID_GetProtocolValue(uint16_t Length)
{
  if (Length == 0)
  {
    pInformation->Ctrl_Info.Usb_wLength = 1;
    return NULL;
  }
  else
  {
    return (uint8_t *)(&ProtocolValue);
  }
}

/*******************************************************************************
* Function Name  : Get_Max_Lun
* Description    : Handle the Get Max Lun request.
* Input          : uint16_t Length.
* Output         : None.
* Return         : None.
*******************************************************************************/
uint8_t *Get_Max_Lun(uint16_t Length)
{
  if (Length == 0)
  {
    pInformation->Ctrl_Info.Usb_wLength = LUN_DATA_LENGTH;
    return 0;
  }
  else
  {
    return (uint8_t *)&Max_Lun;
  }
}



'초보의 아웅다웅 설계하기 > STM32' 카테고리의 다른 글

Tamper 사용  (0) 2018.07.23
다중 이동식 저장장치  (0) 2018.07.23
USB Composite  (0) 2018.07.22
error C1189: #error : MFC does not support WINVER less than 0x0501.  (0) 2018.07.18
Buzzer Melody  (0) 2018.07.16
IAR 에서 고정 영역 SRAM과 ROM 사용  (0) 2018.07.06
Posted by 초보 HW 엔지니어 로망와니

댓글을 달아 주세요

2018.07.18 11:43

Custom_HID PC 프로그램 예제에서 에러문제



error C1189: #error : MFC does not support WINVER less than 0x0501. Please change the definition of WINVER in your project properties or precompiled header. c:\program files (x86)\microsoft visual studio 12.0\vc\atlmfc\include\afxv_w32.h 40 1 UsbHidDemonstrator



USB HID Demonstrator\src\StdAfx.h 에서 아래의 부분을 수정하여야 합니다.



#define WINVER 0x0500

=> 수정

#define WINVER 0x0A00



USB HID Demonstrator.zip


참고 :

http://poorman.tistory.com/144

Posted by 초보 HW 엔지니어 로망와니

댓글을 달아 주세요

2018.07.16 15:13

Buzzer Melody 예제입니다.

멜로디를 위한 테스트 예제로 참고만 하면 될 것 같습니다.


void TIM2_Configuration(void)

{

TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;

NVIC_InitTypeDef NVIC_InitStructure;


/* TIM2 clock enable */

RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);


/* Time base configuration */

TIM_TimeBaseStructure.TIM_Period = 10;  // Overflow Interrupt On 10 usec 타이머주기

TIM_TimeBaseStructure.TIM_Prescaler = 35; // Timer/Count2 Clock = 36Mhz / (35 + 1) = 1Mhz = 1 usec

TIM_TimeBaseStructure.TIM_ClockDivision = 0;

TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; // 카운터모드동작

TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);


  /* TIM2 counter enable */

  TIM_Cmd(TIM2, ENABLE);


/* TIM IT enable */

TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);


/* Enable the TIM2 gloabal Interrupt */

NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;

NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;

NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;

NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;

NVIC_Init(&NVIC_InitStructure);

}


/*

unut : sec

도 0.030578 0.015289 0.007645 0.003822 0.001911 0.000956 0.000478 

C# 0.028862 0.014431 0.007215 0.003608 0.001804 0.000902 0.000451 

레 0.027242 0.013621 0.006810 0.003405 0.001703 0.000851 0.000426 

D# 0.025713 0.012856 0.006428 0.003214 0.001607 0.000804 0.000402 

미 0.024270 0.012135 0.006067 0.003034 0.001517 0.000758 0.000379 

파 0.022908 0.011454 0.005727 0.002863 0.001432 0.000716 0.000358 

F# 0.021622 0.010811 0.005405 0.002703 0.001351 0.000676 0.000338 

솔 0.020408 0.010204 0.005102 0.002551 0.001276 0.000638 0.000319 

G# 0.019263 0.009631 0.004816 0.002408 0.001204 0.000602 0.000301 

라 0.018182 0.009091 0.004545 0.002273 0.001136 0.000568 0.000284 

A# 0.017161 0.008581 0.004290 0.002145 0.001073 0.000536 0.000268 

시 0.016198 0.008099 0.004050 0.002025 0.001012 0.000506 0.000253 

0.000033 0.000065 0.000131 0.000262 0.000523 0.001047 0.002093 

0.000035 0.000069 0.000139 0.000277 0.000554 0.001109 0.002217 

0.000037 0.000073 0.000147 0.000294 0.000587 0.001175 0.002349 

0.000039 0.000078 0.000156 0.000311 0.000622 0.001245 0.002489 

0.000041 0.000082 0.000165 0.000330 0.000659 0.001319 0.002637 

0.000044 0.000087 0.000175 0.000349 0.000698 0.001397 0.002794 

0.000046 0.000092 0.000185 0.000370 0.000740 0.001480 0.002960 

0.000049 0.000098 0.000196 0.000392 0.000784 0.001568 0.003136 

0.000052 0.000104 0.000208 0.000415 0.000831 0.001661 0.003322 

0.000055 0.000110 0.000220 0.000440 0.000880 0.001760 0.003520 

0.000058 0.000117 0.000233 0.000466 0.000932 0.001865 0.003729 

0.000062 0.000123 0.000247 0.000494 0.000988 0.001976 0.003951 

*/


#define MUSIC_REST 0

#define MUSIC_DO 191

#define MUSIC_C_SHARP 180

#define MUSIC_RE 170

#define MUSIC_D_SHARP 161

#define MUSIC_MI 152

#define MUSIC_PA 143

#define MUSIC_F_SHARP 135

#define MUSIC_SOL 128

#define MUSIC_G_SHARP 120

#define MUSIC_RA 114

#define MUSIC_A_SHARP 107

#define MUSIC_SI 101

#define MUSIC_HDO 96



uint32_t Sound = 0;

uint32_t Music = 0;


int main(void)
{
  GPIO_InitTypeDef  GPIO_InitStructure;
  /* System Clocks Configuration */
  RCC_Configuration();
  
  /* Enable the GPIO BUZZER Clock */
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);

  /* Configure the GPIO BUZZER pin */
  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;

  GPIO_Init(GPIOB, &GPIO_InitStructure);

  TIM2_Configuration();

  Music = MUSIC_SOL;
  Delay_Us(100000);
  Music = MUSIC_REST;
  Delay_Us(10000);
  Music = MUSIC_SOL;
  Delay_Us(100000);
  Music = MUSIC_RA;
  Delay_Us(100000);
  Music = MUSIC_REST;
  Delay_Us(10000);
  Music = MUSIC_RA;
  Delay_Us(100000);
  Music = MUSIC_SOL;
  Delay_Us(100000);
  Music = MUSIC_REST;
  Delay_Us(10000);
  Music = MUSIC_SOL;
  Delay_Us(100000);
  Music = MUSIC_MI;
  Delay_Us(100000);
  Delay_Us(100000);

  Music = MUSIC_SOL;
  Delay_Us(100000);
  Music = MUSIC_REST;
  Delay_Us(10000);
  Music = MUSIC_SOL;
  Delay_Us(100000);
  Music = MUSIC_MI;
  Delay_Us(100000);
  Music = MUSIC_REST;
  Delay_Us(10000);
  Music = MUSIC_MI;
  Delay_Us(100000);
  Music = MUSIC_RE;
  Delay_Us(100000);
  Delay_Us(100000);


  Music = MUSIC_SOL;
  Delay_Us(100000);
  Music = MUSIC_REST;
  Delay_Us(10000);
  Music = MUSIC_SOL;
  Delay_Us(100000);
  Music = MUSIC_RA;
  Delay_Us(100000);
  Music = MUSIC_REST;
  Delay_Us(10000);
  Music = MUSIC_RA;
  Delay_Us(100000);
  Music = MUSIC_SOL;
  Delay_Us(100000);
  Music = MUSIC_REST;
  Delay_Us(10000);
  Music = MUSIC_SOL;
  Delay_Us(100000);
  Music = MUSIC_MI;
  Delay_Us(100000);
  Delay_Us(100000);

  Music = MUSIC_SOL;
  Delay_Us(100000);
  Music = MUSIC_MI;
  Delay_Us(100000);
  Music = MUSIC_RE;
  Delay_Us(100000);
  Music = MUSIC_MI;
  Delay_Us(100000);
  Music = MUSIC_DO;
  Delay_Us(100000);
  Delay_Us(100000);
  TIM_Cmd(TIM2, DISABLE);
  GPIOB->BRR = GPIO_Pin_0;
}





stm32f10x_it.c


extern uint32_t Sound;

extern uint32_t Music;


/**

  * @brief  This function handles TIM2 global interrupt request.

  * @param  None

  * @retval None

  */

void TIM2_IRQHandler(void) // 1mS Timer

{

  if (TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET)

  {

    TIM_ClearITPendingBit(TIM2, TIM_IT_Update);

    Sound++;

    if(Sound >= Music){

GPIOB->ODR ^= GPIO_Pin_0;

Sound = 0;

    }

  }

}

Posted by 초보 HW 엔지니어 로망와니

댓글을 달아 주세요