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

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

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));
}

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

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



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

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);

}

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

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;

}

}




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

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++;

}

}

}


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

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


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

고정위치에 바이너리 라이팅하기  (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();

  }

}

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

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;

}



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

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;
  }
}



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

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 엔지니어 로망와니

댓글을 달아 주세요

2018.07.06 10:55


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

.icf

/*-Specials-*/

define symbol __ICFEDIT_intvec_start__ = 0x08000000;

/*-Memory Regions-*/

define symbol __ICFEDIT_region_ROM_start__    = 0x08000000;

define symbol __ICFEDIT_region_ROM_end__      = 0x0800FFFF;

define symbol __ICFEDIT_region_RAM_start__    = 0x20000240;

define symbol __ICFEDIT_region_RAM_end__      = 0x20016FFF;


/*-Sizes-*/

define symbol __ICFEDIT_size_cstack__ = 0x400;

define symbol __ICFEDIT_size_heap__   = 0x200;

/**** End of ICF editor section. ###ICF###*/


/* Rom에서 원하는 함수나 고정값을 넣을 영역 */

define symbol __ICFEDIT_Fixed_region_ROM_start__    = 0x08010000;

define symbol __ICFEDIT_Fixed_region_ROM_end__      = 0x0801FFFF;


/* Ram에서 원하는 변수를 넣을 영역 */

define symbol __ICFEDIT_Fixed_region_SRAM_start__    = 0x20000000;

define symbol __ICFEDIT_Fixed_region_SRAM_end__      = 0x200001FF;




define memory mem with size = 4G;

define region ROM_region      = mem:[from __ICFEDIT_region_ROM_start__   to __ICFEDIT_region_ROM_end__];

define region Fixed_ROM_region      = mem:[from __ICFEDIT_Fixed_region_ROM_start__   to __ICFEDIT_Fixed_region_ROM_end__];

define region Fixed_SRAM_region    = mem:[from __ICFEDIT_Fixed_region_SRAM_start__   to __ICFEDIT_Fixed_region_SRAM_end__];

define region RAM_region      = mem:[from __ICFEDIT_region_RAM_start__   to __ICFEDIT_region_RAM_end__];



place in Fixed_ROM_region {readonly object Fixed_ROM.o};


place in Fixed_SRAM_region   {readwrite section .Fixed_Sram };


initialize by copy { readwrite };

do not initialize  { section .noinit };

initialize by copy { section .Fixed_Sram };


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


Fixed_ROM.c

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

int FixedData(int a, int b)

{

return (a+b);

}

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


Fixed_SRAM.c

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

#pragma section =".Fixed_Sram"


#pragma default_variable_attributes = @ ".Fixed_Sram"

uint32_t FixedSRAMData[10];


/* Stop placing data in section Fixed_SRAM_region */

#pragma default_variable_attributes =

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



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

댓글을 달아 주세요

2018.06.28 21:58

 STM32L432가 저가의 제품이라 사용하려고 하고 있습니다.

그런데 Read Protect 기능을 사용하면 기존에 라이팅 되어 있는 프로그램이 다 사라집니다. 당황스럽네요.

STM32F1XX 제품군에서 확인하면 괜찮은데 이 제품에서만 그러네요.(사라진게 아니라 동작을 안한거였슴니다)


놀랍습니다.

어제 질문글을 올렸는데 오늘 답변이 왔네요.

니가 무슨말 하는지 모르겠다라구요.. ㅠㅠ

제 영어실력이 딸려서 ㅠㅠ

어제까지만 해도 비관적 안티였었는데 하루만에 ST 찬양합니다.

그 후에 20분 간격으로 답변을 주고 받을 수 있었습니다.

채팅하는 줄....

 

Dear customer,

In relation to the read out protection in the reference manual of STM32L432KC, it is mentioned as follows :

"If the read protection is set while the debugger is still connected through JTAG/SWD, apply a POR (power-on reset) instead of a system reset."

To operate MCU after setting RDP Level1 using ST-Link utility, you need to physically reset MCU power. 

Thank you.


전원을 JTAG쪽에 안 넣고 따로 넣어도 안된다고 문의했더니 또 답변이 옵니다. 의미는 없었지만..


Dear customer,

Did you try a system reset or POR(power-on reset)? 

the below is the descripotion of ROP in the reference manual. 

"The read protection is activated by setting the RDP option byte and then, by applying a system reset to reload the new RDP option byte."

Thank you.


그러다 아 SWD 신호라인에 역으로 전원이 인가돼서 그러는 건 아닐까? 하고 신호선을 칼로 잘라냈더니 됩니다.

=> SWD나 JTAG단자를 완전 분리해야만 동작하는 부분이었습니다.

....( - _-);; 죄송합니다.

 

 그리고 ST에서 제공하는 UART 라이팅프로그램에서는 지원하지 않네요.

예전 버그들이 생각납니다.

UART 라이팅 프로그램 버그(하위버젼으로 내려서 사용해야했었던)였던가? 한참을 고쳐주지 않았던 느긋한? ST사의 대응이 생각나네요.

 

구글링을 하다보니 STM32L432제품을 다운로드할 수 있는 UART 프로그램이 있었습니다. 기존과 다르게 자동으로 칩을 선택해주는 게 아니라 사용하는 칩을 선택하여야 합니다. 그리고 정식본인지는 잘 모르겠습니다.... 판단은 각자가..

STMFlashLoader Demo_V2.9.0RC4.zip


ST에서 제공하는 STMFlashLoader

https://www.st.com/en/development-tools/flasher-stm32.html



나중에 검색해보시면 아시겠지만 Read Protection에도 보안 이슈가 있습니다.

대단한 놈들...

STM32L4 시리즈에서 FireWall이라는 옵션이 생겼는데 프로텍션과 비슷합니다.

ROM과 RAM 영역을 나눠서(*.icf(iar)나 *.sct(keil)) Code나 Data를 넣고 그 영역을 방화벽으로 접근못하게 하는 것 같습니다. 우왕...

Protection과 함께 쓰기를 권장하는데 프로그램에 설정해주고 하는 게 귀찮아서 크리한 거 아니면 안 쓸것 같습니다. 내부에 꼭 가지고 있어야 하는 SSP 같은 거 아니면 2중으로 하는 번거로움으로 인해...


결론은 ST 찬양합니다. 

갈 수록 (대응이) 좋아지네요. 개인적인 질문에도 답변해주는 거에 감탄!!! 

브x드컴 같은 곳은 중소기업이나 수량 적은 곳 사지말라고 하는 느낌인데... 무슨 포럼 가입도 안 시켜줘.... 

갓 ST... 







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

댓글을 달아 주세요

2018.06.26 13:34

STM32L4xx에서 BrownOut 설정

 HAL_FLASH_Unlock()을 하지 않고  HAL_FLASH_OB_Unlock()만을 하였더니 계속 에러가 발생하였습니다. 가만 생각해보면 당연한건데 그걸 놓쳤었네요.

전압레벨 설정은 아래와 같고 기본은 1.7V입니다.

ReadOut Protect도 같이 설정되어 있습니다.

 

#define OB_BOR_LEVEL_0            ((uint32_t)FLASH_OPTR_BOR_LEV_0)     /*!< Reset level threshold is around 1.7V */
#define OB_BOR_LEVEL_1            ((uint32_t)FLASH_OPTR_BOR_LEV_1)     /*!< Reset level threshold is around 2.0V */
#define OB_BOR_LEVEL_2            ((uint32_t)FLASH_OPTR_BOR_LEV_2)     /*!< Reset level threshold is around 2.2V */
#define OB_BOR_LEVEL_3            ((uint32_t)FLASH_OPTR_BOR_LEV_3)     /*!< Reset level threshold is around 2.5V */
#define OB_BOR_LEVEL_4            ((uint32_t)FLASH_OPTR_BOR_LEV_4)     /*!< Reset level threshold is around 2.8V */

 




#define USRCONFIGMASK 0xFFFFF8FF

#define BORLEVELMASK 0x00000700

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

* Function Name : 

* Parameters    : None

* Return        : None

* Description   : 

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

uint32_t Get_USRConfig(void) 

{

FLASH_OBProgramInitTypeDef FLASH_Handle;

/* Read option bytes */

HAL_FLASHEx_OBGetConfig(&FLASH_Handle);

return (FLASH_Handle.USERConfig & USRCONFIGMASK);

}


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

* Function Name : 

* Parameters    : None

* Return        : None

* Description   : 

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

uint32_t Get_BORConfig(void)

{

FLASH_OBProgramInitTypeDef FLASH_Handle;

/* Read option bytes */

HAL_FLASHEx_OBGetConfig(&FLASH_Handle);


return (FLASH_Handle.USERConfig & BORLEVELMASK);

}

 

void Config_BOR(void)

{

uint32_t BORTimeout = BOR_FLAG_TIMEOUT; 

FLASH_OBProgramInitTypeDef FLASH_Handle; 

HAL_FLASHEx_OBGetConfig(&FLASH_Handle); 

DEBUGPRINT("USERConfig %X\r\n", FLASH_Handle.USERConfig); 

DEBUGPRINT("FLASH_Handle.RDPLevel %X \r\n", FLASH_Handle.RDPLevel); 

if(Get_BORConfig() != BORLEVEL){ 

FLASH_Handle.USERConfig = (Get_USRConfig() | BORLEVEL); 

FLASH_Handle.OptionType = (OPTIONBYTE_USER | OPTIONBYTE_RDP); 

FLASH_Handle.USERType = OB_USER_BOR_LEV; 

FLASH_Handle.RDPLevel = OB_RDP_LEVEL_1; 

while (HAL_FLASH_Unlock() != HAL_OK){ 

if((BORTimeout--) == 0){DEBUGPRINT("HAL_FLASH_Unlock Fail\r\n");break;}

DEBUGPRINT("HAL_FLASH_Unlock\r\n"); 

    __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_OPTVERR); 

BORTimeout = BOR_FLAG_TIMEOUT; 

while (HAL_FLASH_OB_Unlock() != HAL_OK){ 

if((BORTimeout--) == 0){DEBUGPRINT("HAL_FLASH_OB_Unlock Fail\r\n");break;}

DEBUGPRINT("USERConfig %X\r\n", FLASH_Handle.USERConfig); 

DEBUGPRINT("FLASH_Handle.RDPLevel %X \r\n", FLASH_Handle.RDPLevel); 

BORTimeout = BOR_FLAG_TIMEOUT; 

while (HAL_FLASHEx_OBProgram(&FLASH_Handle) != HAL_OK){ 

if((BORTimeout--) == 0){DEBUGPRINT("HAL_FLASHEx_OBProgram Fail\r\n");break;}

DEBUGPRINT("HAL_FLASHEx_OBProgram\r\n"); 

BORTimeout = BOR_FLAG_TIMEOUT; 

while (HAL_FLASH_OB_Lock() != HAL_OK){ 

if((BORTimeout--) == 0){DEBUGPRINT("HAL_FLASH_OB_Lock Fail\r\n");break;}

DEBUGPRINT("HAL_FLASH_OB_Lock\r\n"); 

BORTimeout = BOR_FLAG_TIMEOUT; 

while (HAL_FLASH_Lock() != HAL_OK){ 

if((BORTimeout--) == 0){DEBUGPRINT("HAL_FLASH_Lock Fail\r\n");break;}

DEBUGPRINT("HAL_FLASH_Lock\r\n"); 

}

}

}

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

댓글을 달아 주세요

2018.05.30 10:04

Low Layer Driver을 사용한 ADC

들어오는 ADC 값의 움직임을 크게 주기 위해 샘플링 주기를 짧게 가져왔습니다.(LL_ADC_SAMPLINGTIME_2CYCLES_5)

 

int main(void)
{

 uint32_t nBuf[128];

 uint8_t i;


  /* Configure the system clock to 80 MHz */
 SystemClock_LLConfig();
  /* ADC Configuration */
 ADC_Configuration(); 

 while(1){

  GetADC1(chBuf);

  for(i = 0; i< 11; i++){

   UART1_printf("ADC0 =%02X \r\n", chBuf[i]);

  }
 }

}

 

 

 

#include "math.h"
#include "usr_adc.h"
#include "usr_usart.h"

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


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

/* Variables for ADC conversion data */
__IO uint16_t aADCxConvertedData[ADC_CONVERTED_DATA_BUFFER_SIZE]; /* ADC group regular conversion data */


/*******************************************************************************
* Function Name :
* Parameters    : None
* Return        : None
* Description   :
*******************************************************************************/
void ADC_Configuration(void)
{
 ADCDMA_Init(eADCIntDisable);
 ADC_Init(eADCIntDisable);
 Activate_ADC();
}

/*******************************************************************************
* Function Name :
* Parameters    : None
* Return        : None
* Description   :
*******************************************************************************/
void ADCDMA_Init(const ADCEnableState a_chInt)
{
  /*## Configuration of DMA ##################################################*/
  /* Enable the peripheral clock of DMA */
  LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_DMA1);
 
  /* Configure the DMA transfer */
  /*  - DMA transfer in circular mode to match with ADC configuration:        */
  /*    DMA unlimited requests.                                               */
  /*  - DMA transfer from ADC without address increment.                      */
  /*  - DMA transfer to memory with address increment.                        */
  /*  - DMA transfer from ADC by half-word to match with ADC configuration:   */
  /*    ADC resolution 12 bits.                                               */
  /*  - DMA transfer to memory by half-word to match with ADC conversion data */
  /*    buffer variable type: half-word.                                      */
  LL_DMA_ConfigTransfer(DMA1,
                        LL_DMA_CHANNEL_1,
                        LL_DMA_DIRECTION_PERIPH_TO_MEMORY |
                        LL_DMA_MODE_CIRCULAR              |
                        LL_DMA_PERIPH_NOINCREMENT         |
                        LL_DMA_MEMORY_INCREMENT           |
                        LL_DMA_PDATAALIGN_HALFWORD        |
                        LL_DMA_MDATAALIGN_HALFWORD        |
                        LL_DMA_PRIORITY_HIGH               );
 
  /* Select ADC as DMA transfer request */
  LL_DMA_SetPeriphRequest(DMA1,
                          LL_DMA_CHANNEL_1,
                          LL_DMA_REQUEST_0);
 
  /* Set DMA transfer addresses of source and destination */
  LL_DMA_ConfigAddresses(DMA1,
                         LL_DMA_CHANNEL_1,
                         LL_ADC_DMA_GetRegAddr(ADC1, LL_ADC_DMA_REG_REGULAR_DATA),
                         (uint32_t)&aADCxConvertedData,
                         LL_DMA_DIRECTION_PERIPH_TO_MEMORY);
 
  /* Set DMA transfer size */
  LL_DMA_SetDataLength(DMA1,
                       LL_DMA_CHANNEL_1,
                       ADC_CONVERTED_DATA_BUFFER_SIZE);
 
  /*## Activation of DMA #####################################################*/
  /* Enable the DMA transfer */
  LL_DMA_EnableChannel(DMA1,
                       LL_DMA_CHANNEL_1);


 if(a_chInt == eADCIntEnable){
  /* Enable DMA transfer interruption: transfer complete */
  LL_DMA_EnableIT_TC(DMA1,
            LL_DMA_CHANNEL_1);
  
  /* Enable DMA transfer interruption: transfer error */
  LL_DMA_EnableIT_TE(DMA1,
            LL_DMA_CHANNEL_1);

  /*## Configuration of NVIC #################################################*/
  /* Configure NVIC to enable DMA interruptions */
  NVIC_SetPriority(DMA1_Channel1_IRQn, 1);  /* DMA IRQ lower priority than ADC IRQ */
  NVIC_EnableIRQ(DMA1_Channel1_IRQn);
 }              
}

/*******************************************************************************
* Function Name :
* Parameters    :
* Return        : None
* Description   :
*******************************************************************************/
void ADC_Init(const ADCEnableState a_chInt)
{
  __IO uint32_t wait_loop_index = 0;
 
  /*## Configuration of GPIO used by ADC channels ############################*/
 LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_GPIOA);
 LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_GPIOB);

  /* Configure GPIO in analog mode to be used as ADC input */
  LL_GPIO_SetPinMode(GPIOA, LL_GPIO_PIN_1, LL_GPIO_MODE_ANALOG);//ADC_IN1
  LL_GPIO_SetPinMode(GPIOA, LL_GPIO_PIN_2, LL_GPIO_MODE_ANALOG);//ADC_IN2
  LL_GPIO_SetPinMode(GPIOA, LL_GPIO_PIN_3, LL_GPIO_MODE_ANALOG);//ADC_IN3
  LL_GPIO_SetPinMode(GPIOA, LL_GPIO_PIN_4, LL_GPIO_MODE_ANALOG);//ADC_IN4
  LL_GPIO_SetPinMode(GPIOA, LL_GPIO_PIN_5, LL_GPIO_MODE_ANALOG);//ADC_IN5
  LL_GPIO_SetPinMode(GPIOA, LL_GPIO_PIN_6, LL_GPIO_MODE_ANALOG);//ADC_IN6
  LL_GPIO_SetPinMode(GPIOA, LL_GPIO_PIN_7, LL_GPIO_MODE_ANALOG);//ADC_IN7
 
  LL_GPIO_SetPinMode(GPIOB, LL_GPIO_PIN_0, LL_GPIO_MODE_ANALOG);//ADC_IN8
  LL_GPIO_SetPinMode(GPIOB, LL_GPIO_PIN_1, LL_GPIO_MODE_ANALOG);//ADC_IN9


  /*## Configuration of ADC ##################################################*/
  /* Enable ADC clock (core clock) */
  LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_ADC);
 
  if(__LL_ADC_IS_ENABLED_ALL_COMMON_INSTANCE() == 0)
  {
    /* Set ADC clock (conversion clock) common to several ADC instances */
    LL_ADC_SetCommonClock(__LL_ADC_COMMON_INSTANCE(ADC1), LL_ADC_CLOCK_SYNC_PCLK_DIV2);
    /* Set ADC measurement path to internal channels */
    LL_ADC_SetCommonPathInternalCh(__LL_ADC_COMMON_INSTANCE(ADC1), (LL_ADC_PATH_INTERNAL_VREFINT | LL_ADC_PATH_INTERNAL_TEMPSENSOR));
   
    /* Delay for ADC temperature sensor stabilization time.                   */
    wait_loop_index = ((LL_ADC_DELAY_TEMPSENSOR_STAB_US * (SystemCoreClock / (100000 * 2))) / 10);
    while(wait_loop_index != 0)
    {
      wait_loop_index--;
    }
    /* Set ADC multimode configuration */
    // LL_ADC_SetMultimode(__LL_ADC_COMMON_INSTANCE(ADC1), LL_ADC_MULTI_INDEPENDENT);
   
    /* Set ADC multimode DMA transfer */
    // LL_ADC_SetMultiDMATransfer(__LL_ADC_COMMON_INSTANCE(ADC1), LL_ADC_MULTI_REG_DMA_EACH_ADC);
   
    /* Set ADC multimode: delay between 2 sampling phases */
    // LL_ADC_SetMultiTwoSamplingDelay(__LL_ADC_COMMON_INSTANCE(ADC1), LL_ADC_MULTI_TWOSMP_DELAY_1CYCLE);
  }
 
  /*## Configuration of ADC hierarchical scope: ADC instance #################*/
  if (LL_ADC_IsEnabled(ADC1) == 0)
  {
   /* Note: Call of the functions below are commented because they are       */
    /*       useless in this example:                                         */
    /*       setting corresponding to default configuration from reset state. */
   
    /* Set ADC data resolution */
    // LL_ADC_SetResolution(ADC1, LL_ADC_RESOLUTION_12B);
   
    /* Set ADC conversion data alignment */
    // LL_ADC_SetResolution(ADC1, LL_ADC_DATA_ALIGN_RIGHT);
   
    /* Set ADC low power mode */
    // LL_ADC_SetLowPowerMode(ADC1, LL_ADC_LP_MODE_NONE);
   
    /* Set ADC selected offset number: channel and offset level */
    // LL_ADC_SetOffset(ADC1, LL_ADC_OFFSET_1, LL_ADC_CHANNEL_9, 0x000);
  }
 
  /*## Configuration of ADC hierarchical scope: ADC group regular ############*/
  if ((LL_ADC_IsEnabled(ADC1) == 0)               ||
      (LL_ADC_REG_IsConversionOngoing(ADC1) == 0)   )
  {
    /* Set ADC group regular trigger source */
    LL_ADC_REG_SetTriggerSource(ADC1, LL_ADC_REG_TRIG_SOFTWARE);
   
    /* Set ADC group regular trigger polarity */
    // LL_ADC_REG_SetTriggerEdge(ADC1, LL_ADC_REG_TRIG_EXT_RISING);
   
    /* Set ADC group regular continuous mode */
    LL_ADC_REG_SetContinuousMode(ADC1, LL_ADC_REG_CONV_SINGLE);
//    LL_ADC_REG_SetContinuousMode(ADC1, LL_ADC_REG_CONV_CONTINUOUS);
   
    /* Set ADC group regular conversion data transfer */
    // LL_ADC_REG_SetDMATransfer(ADC1, LL_ADC_REG_DMA_TRANSFER_NONE);
    LL_ADC_REG_SetDMATransfer(ADC1, LL_ADC_REG_DMA_TRANSFER_UNLIMITED);
   
    /* Set ADC group regular overrun behavior */
    LL_ADC_REG_SetOverrun(ADC1, LL_ADC_REG_OVR_DATA_OVERWRITTEN);
   
    /* Set ADC group regular sequencer length and scan direction */
//    LL_ADC_REG_SetSequencerLength(ADC1, LL_ADC_REG_SEQ_SCAN_DISABLE);
    LL_ADC_REG_SetSequencerLength(ADC1, LL_ADC_REG_SEQ_SCAN_ENABLE_11RANKS);
   
    /* Set ADC group regular sequencer discontinuous mode */
    // LL_ADC_REG_SetSequencerDiscont(ADC1, LL_ADC_REG_SEQ_DISCONT_DISABLE);
   
    /* Set ADC group regular sequence: channel on the selected sequence rank. */
    LL_ADC_REG_SetSequencerRanks(ADC1, LL_ADC_REG_RANK_1, LL_ADC_CHANNEL_6);
    LL_ADC_REG_SetSequencerRanks(ADC1, LL_ADC_REG_RANK_2, LL_ADC_CHANNEL_7);
    LL_ADC_REG_SetSequencerRanks(ADC1, LL_ADC_REG_RANK_3, LL_ADC_CHANNEL_8);
    LL_ADC_REG_SetSequencerRanks(ADC1, LL_ADC_REG_RANK_4, LL_ADC_CHANNEL_9);
    LL_ADC_REG_SetSequencerRanks(ADC1, LL_ADC_REG_RANK_5, LL_ADC_CHANNEL_10);
    LL_ADC_REG_SetSequencerRanks(ADC1, LL_ADC_REG_RANK_6, LL_ADC_CHANNEL_11);
    LL_ADC_REG_SetSequencerRanks(ADC1, LL_ADC_REG_RANK_7, LL_ADC_CHANNEL_12);
    LL_ADC_REG_SetSequencerRanks(ADC1, LL_ADC_REG_RANK_8, LL_ADC_CHANNEL_15);
    LL_ADC_REG_SetSequencerRanks(ADC1, LL_ADC_REG_RANK_9, LL_ADC_CHANNEL_16);
    LL_ADC_REG_SetSequencerRanks(ADC1, LL_ADC_REG_RANK_10, LL_ADC_CHANNEL_VREFINT);
    LL_ADC_REG_SetSequencerRanks(ADC1, LL_ADC_REG_RANK_11, LL_ADC_CHANNEL_TEMPSENSOR);
  }

  /*## Configuration of ADC hierarchical scope: ADC group injected ###########*/
  if ((LL_ADC_IsEnabled(ADC1) == 0)               ||
      (LL_ADC_INJ_IsConversionOngoing(ADC1) == 0)   )
  {
    /* Note: Call of the functions below are commented because they are       */
    /*       useless in this example:                                         */
    /*       setting corresponding to default configuration from reset state. */
   
    /* Set ADC group injected trigger source */
    // LL_ADC_INJ_SetTriggerSource(ADC1, LL_ADC_INJ_TRIG_SOFTWARE);
   
    /* Set ADC group injected trigger polarity */
    // LL_ADC_INJ_SetTriggerEdge(ADC1, LL_ADC_INJ_TRIG_EXT_RISING);
   
    /* Set ADC group injected conversion trigger  */
    // LL_ADC_INJ_SetTrigAuto(ADC1, LL_ADC_INJ_TRIG_INDEPENDENT);
   
    /* Set ADC group injected contexts queue mode */
    /* Note: If ADC group injected contexts queue are enabled, configure      */
    /*       contexts using function "LL_ADC_INJ_ConfigQueueContext()".       */
    // LL_ADC_INJ_SetQueueMode(ADC1, LL_ADC_INJ_QUEUE_DISABLE);
   
    /* Set ADC group injected sequencer */
    /* Note: On this STM32 serie, ADC group injected sequencer is             */
    /*       fully configurable: sequencer length and each rank               */
    /*       affectation to a channel are configurable.                       */
    /*       Refer to description of function                                 */
    /*       "LL_ADC_INJ_SetSequencerLength()".                               */
   
    /* Set ADC group injected sequencer length and scan direction */
    // LL_ADC_INJ_SetSequencerLength(ADC1, LL_ADC_INJ_SEQ_SCAN_DISABLE);
   
    /* Set ADC group injected sequencer discontinuous mode */
    // LL_ADC_INJ_SetSequencerDiscont(ADC1, LL_ADC_INJ_SEQ_DISCONT_DISABLE);
   
    /* Set ADC group injected sequence: channel on the selected sequence rank. */
    // LL_ADC_INJ_SetSequencerRanks(ADC1, LL_ADC_INJ_RANK_1, LL_ADC_CHANNEL_9);
  }
 
 
  /*## Configuration of ADC hierarchical scope: channels #####################*/
  if ((LL_ADC_IsEnabled(ADC1) == 0)                    ||
      ((LL_ADC_REG_IsConversionOngoing(ADC1) == 0) &&
       (LL_ADC_INJ_IsConversionOngoing(ADC1) == 0)   )   )
  {
  LL_ADC_SetChannelSamplingTime(ADC1, LL_ADC_CHANNEL_6, LL_ADC_SAMPLINGTIME_2CYCLES_5);
  LL_ADC_SetChannelSamplingTime(ADC1, LL_ADC_CHANNEL_7, LL_ADC_SAMPLINGTIME_2CYCLES_5);
  LL_ADC_SetChannelSamplingTime(ADC1, LL_ADC_CHANNEL_8, LL_ADC_SAMPLINGTIME_2CYCLES_5);
  LL_ADC_SetChannelSamplingTime(ADC1, LL_ADC_CHANNEL_9, LL_ADC_SAMPLINGTIME_2CYCLES_5);
  LL_ADC_SetChannelSamplingTime(ADC1, LL_ADC_CHANNEL_10, LL_ADC_SAMPLINGTIME_2CYCLES_5);
  LL_ADC_SetChannelSamplingTime(ADC1, LL_ADC_CHANNEL_11, LL_ADC_SAMPLINGTIME_2CYCLES_5);
  LL_ADC_SetChannelSamplingTime(ADC1, LL_ADC_CHANNEL_12, LL_ADC_SAMPLINGTIME_2CYCLES_5);
  LL_ADC_SetChannelSamplingTime(ADC1, LL_ADC_CHANNEL_15, LL_ADC_SAMPLINGTIME_2CYCLES_5);
  LL_ADC_SetChannelSamplingTime(ADC1, LL_ADC_CHANNEL_16, LL_ADC_SAMPLINGTIME_2CYCLES_5);
    LL_ADC_SetChannelSamplingTime(ADC1, LL_ADC_CHANNEL_VREFINT, LL_ADC_SAMPLINGTIME_2CYCLES_5);
    LL_ADC_SetChannelSamplingTime(ADC1, LL_ADC_CHANNEL_TEMPSENSOR, LL_ADC_SAMPLINGTIME_2CYCLES_5);
   
  }
 
  /*## Configuration of ADC transversal scope: analog watchdog ###############*/ 
  /* Set ADC analog watchdog channels to be monitored */
  // LL_ADC_SetAnalogWDMonitChannels(ADC1, LL_ADC_AWD1, LL_ADC_AWD_DISABLE);
 
  /* Set ADC analog watchdog thresholds */
  // LL_ADC_ConfigAnalogWDThresholds(ADC1, LL_ADC_AWD1, 0xFFF, 0x000);
 
 
  /*## Configuration of ADC transversal scope: oversampling ##################*/
 
  /* Set ADC oversampling scope */
  // LL_ADC_SetOverSamplingScope(ADC1, LL_ADC_OVS_DISABLE);
 
  /* Set ADC oversampling parameters */
  // LL_ADC_ConfigOverSamplingRatioShift(ADC1, LL_ADC_OVS_RATIO_2, LL_ADC_OVS_SHIFT_NONE);
 
  /*## Configuration of ADC transversal scope: oversampling ##################*/
  /*## Configuration of ADC interruptions ####################################*/
  /* Enable interruption ADC group regular overrun */
  if(a_chInt == eADCIntEnable){
  /*## Configuration of NVIC #################################################*/
  /* Configure NVIC to enable ADC1 interruptions */
   NVIC_SetPriority(ADC1_2_IRQn, 0); /* ADC IRQ greater priority than DMA IRQ */
   NVIC_EnableIRQ(ADC1_2_IRQn);

   LL_ADC_EnableIT_EOS(ADC1);

   LL_ADC_EnableIT_OVR(ADC1); 
  }
}

/*******************************************************************************
* Function Name :
* Parameters    : None
* Return        : None
* Description   :
*******************************************************************************/
void ConversionStartPoll_ADC_GrpRegular(void)
{
  #if (USE_TIMEOUT == 1)
  uint32_t Timeout = 0; /* Variable used for timeout management */
  #endif /* USE_TIMEOUT */
  
  if ((LL_ADC_IsEnabled(ADC1) == 1)               &&
      (LL_ADC_IsDisableOngoing(ADC1) == 0)        &&
      (LL_ADC_REG_IsConversionOngoing(ADC1) == 0)   )
  {
    LL_ADC_REG_StartConversion(ADC1);
  }
  else
  {
    /* Error: ADC conversion start could not be performed */

  }
 
  #if (USE_TIMEOUT == 1)
  Timeout = ADC_UNITARY_CONVERSION_TIMEOUT_MS;
  #endif /* USE_TIMEOUT */
 
  while (LL_ADC_IsActiveFlag_EOC(ADC1) == 0)
  {
  #if (USE_TIMEOUT == 1)
    /* Check Systick counter flag to decrement the time-out value */
    if (LL_SYSTICK_IsActiveCounterFlag())
    {
      if(Timeout-- == 0)
      {

      }
    }
  #endif /* USE_TIMEOUT */
  }

  LL_ADC_ClearFlag_EOC(ADC1); 
}

/*******************************************************************************
* Function Name :
* Description   :
* Parameters    :
* Return        :
* Description   :
*******************************************************************************/
int32_t GetADC1(uint16_t *chpADC)
{
 uint8_t ADCLoop;
 
  if ((LL_ADC_IsEnabled(ADC1) == 1)               &&
      (LL_ADC_IsDisableOngoing(ADC1) == 0)        &&
      (LL_ADC_REG_IsConversionOngoing(ADC1) == 0)   )
  {
    LL_ADC_REG_StartConversion(ADC1);
  }
  else
  {
    /* Error: ADC conversion start could not be performed */
    UART1_printf("Error\r\n");
  }
 
 for(ADCLoop = 0; ADCLoop < ADC_CONVERTED_DATA_BUFFER_SIZE; ADCLoop++){
  chpADC[ADCLoop] = __LL_ADC_CALC_DATA_TO_VOLTAGE(VDDA_APPLI, aADCxConvertedData[ADCLoop], LL_ADC_RESOLUTION_12B);
 }

 return __LL_ADC_CALC_TEMPERATURE(VDDA_APPLI, aADCxConvertedData[ADC_CONVERTED_DATA_BUFFER_SIZE - 1], LL_ADC_RESOLUTION_12B);
}

/*******************************************************************************
* Function Name :
* Parameters    : None
* Return        : None
* Description   :
*******************************************************************************/
void AdcGrpRegularOverrunError_Callback(void)
{
  /* Disable ADC group regular overrun interruption */
  LL_ADC_DisableIT_OVR(ADC1);
}

/*******************************************************************************
* Function Name :
* Parameters    : None
* Return        : None
* Description   :
*******************************************************************************/
void AdcGrpRegularSequenceConvComplete_Callback(void)
{
}

/*******************************************************************************
* Function Name :
* Parameters    : None
* Return        : None
* Description   :
*******************************************************************************/
void AdcDmaTransferError_Callback(void)
{
}

/*******************************************************************************
* Function Name :
* Parameters    : None
* Return        : None
* Description   :
*******************************************************************************/
void AdcDmaTransferComplete_Callback(void)
{
}

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

댓글을 달아 주세요

  1. uocraft 2018.06.19 18:51 신고  댓글주소  수정/삭제  댓글쓰기

    ADC값의 움직임이 커지겠군요

2018.05.17 08:59

WWDG에서 Watchdog 발생시 클리어 처리

WWDG 사용중에 특정 목적에서는 WWDG가 동작하지 않아야하는데 이런 목적으로 사용할 경우 인터럽트에서 클리어 처리 해주어야 합니다. WWDG나 IWDG는 동작하도록 한번 설정을 하면 플래그에 다시 사용히자 않도록 설정을 하여도 되지 않습니다. 이럴 때를 위해서 인터럽트과 인터럽트가 아닌 곳에서 처리하도록 양쪽에 처리를 하였습니다.

(STM32L432에서 구현된 부분)

메인 .c

tFunc_Typedef  Func_Operate[] =
{
 /* Random Source */
// {GenRandom, "GetADC", 0}, 

 /* UART */
 {GetuPacket, "GetUartPacket", 0},
 /* SPI */
 {GetsPacket, "GetSPIPacket", 0},

 /* Input Button - Erase Function */
 {InputStatus, "InputStatus", 0},
 
 /* Output Status Pulse Wave For Normal Operation */
 {OutputStatus, "OutputStatus", 0},
 
 /* WatchDog Timer Reset */
 {SetWWDGCount, "SetWWDGCount", 0},
};

 

void main(void)

{

 /* Watch Dog Timer Configuration */
 WWDG_Configuration();
 OUTPUT_On(OUTPUTPIN_2);  
 while(1){
    if(Func_Operate[FuncIndex++].OperateFunc() == exit){break;}
  if (FuncIndex >= COUNT_OF_FUNCTION(Func_Operate)){
   FuncIndex = 0;
  }
 }

인터럽트가 발생하지 않으면서 처리해야하는 부분

....

}

 

인터럽트 처리 .c

void WWDG_IRQHandler(void)
{
  if(LL_WWDG_IsActiveFlag_EWKUP(WWDG) == 1)
  {
    /* Clear the Autoreload match interrupt flag */
    LL_WWDG_ClearFlag_EWKUP(WWDG);
   
    WWDG_Callback();
  }
}

 

관련 제어 파일 .c

/* Includes ------------------------------------------------------------------*/
#include "usr_wwdg.h"
#include "usr_usart.h"

#include "stm32l4xx_ll_bus.h"
#include "stm32l4xx_ll_rcc.h"
#include "stm32l4xx_ll_wwdg.h"

uint8_t g_chWWDGEnableFlag = 0;
/*******************************************************************************
* Function Name :
* Parameters    :
* Return        : None
* Description   :
*******************************************************************************/
void WWDG_Reset(void)
{
  if (LL_RCC_IsActiveFlag_WWDGRST()) {
    /* clear WWDG reset flag */
    LL_RCC_ClearResetFlags();
  }
}

/*******************************************************************************
* Function Name :
* Parameters    :
* Return        : None
* Description   :
*******************************************************************************/
void WWDG_init(void)
{
  /* Enable the peripheral clock of DBG register (uncomment for debug purpose) */
  /*LL_DBGMCU_APB1_GRP1_FreezePeriph(LL_DBGMCU_APB1_GRP1_WWDG_STOP); */
 
  /* Enable the peripheral clock WWDG */
  LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_WWDG);

  /* Configure WWDG */
  LL_WWDG_SetPrescaler(WWDG, LL_WWDG_PRESCALER_8);
  LL_WWDG_SetWindow(WWDG, WWDGCNT);                
  LL_WWDG_SetCounter(WWDG, WWDGCNT);          
  LL_WWDG_Enable(WWDG);          

 
 NVIC_SetPriority(WWDG_IRQn, 0); 
 NVIC_EnableIRQ(WWDG_IRQn);
 
 LL_WWDG_EnableIT_EWKUP(WWDG);  
}

/*******************************************************************************
* Function Name :
* Parameters    : None
* Return        : None
* Description   :
void WWDG_IRQHandler(void)
{
  if(LL_WWDG_IsActiveFlag_EWKUP(WWDG) == 1)
  {
    LL_WWDG_ClearFlag_EWKUP(WWDG);
   
    WWDG_Callback();
  }
}
*******************************************************************************/ 
void WWDG_Callback(void)
{
 if(g_chWWDGEnableFlag == 0){
  SetWWDGCount();
 }
 else{
  UART1_printf("SetWWDG Non Clear\r\n");
 }
}

/*******************************************************************************
* Function Name :
* Parameters    :
* Return        : None
* Description   :
*******************************************************************************/
void GetWWDGCount(void)
{
 LL_WWDG_GetCounter(WWDG);
}

/*******************************************************************************
* Function Name :
* Parameters    :
* Return        : None
* Description   :
*******************************************************************************/
uint32_t SetWWDGCount(void)
{
 LL_WWDG_SetCounter(WWDG, WWDGCNT);
 
 return 1;
}

/*******************************************************************************
* Function Name :
* Parameters    :
* Return        : None
* Description   :
*******************************************************************************/
void WWDG_Configuration(void)
{
 WWDG_Reset();
  WWDG_init();
 g_chWWDGEnableFlag = 1;
}

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

댓글을 달아 주세요